I have the following code which works perfectly but I need an onblur statement if a user clicks away from the dropdown, therefore taking it back to its original state – but have tried to implement this and have no idea where to begin really.
here’s the code:
<script>
$(document).ready(function(){
var choices = "<select class='choices'>"
+"<option value='Choice 1'>Choice 1</option>"
+"<option value='Choice 2'>Choice 2</option>"
+"<option value='Choice 3'>Choice 3</option>"
+"<option value='Choice 4'>Choice 4</option>"
+"</select>";
$(".update").click(function() {
var $this = $(this),
currentChoice;
// don't continue if there's already a select in this cell
if ($this.find("select").length != 0)
return;
currentChoice = $this.html();
var $choices = $(choices);
$this.empty().append($choices);
$choices.val(currentChoice);
});
$(document).on("change", ".choices", function() {
var $this = $(this);
$this.parent().html($this.val());
return false;
});
});
</script>
<table id="list">
<tr>
<td>Film Name 1</td>
<td class="update">Choice 1</td>
</tr>
<tr>
<td>File Name 2</td>
<td class="update">Choice 3</td>
</tr>
<!-- etc -->
</table>
Also, can i then use onchange="this.form.submit();" to submit the change to my mysql db?
Your case is bit tricky, from what I saw you have no choice but handle the global
clickevent of the document, as theblurdoesn’t really work as expected for drop down element in my testings.So in the global click event start a timer that reset the value and in the click event of the drop down itself and its parent cell cancel the timer so that the user can still select.
The code you have to add is:
Live test case.
Edit: in order to hide the previously opened drop down lists, you need to do that in the click event:
Updated jsFiddle.