select list modified on-the-fly doesn't fire onChange() for new first element
In the code below, I'm using jquery 1.4.1 to modify the options in a select list when the user clicks on the list (replacing the single Old item with three New items). Selecting either New 2 or New 3 correctly fires the change() method (and show the alert), but selecting "New 1" does not. What am I missing? Thanks.
<html>
<head>
<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
<script>
$(document).ready(function() {
$("#dropdown").mousedown(function() {
$(this).empty();
$(this).append($("<option></option>").attr("value",100).text("New 1"));
$(this).append($("<option></option>").attr("value",200).text("New 2"));
$(this).append($("<option></option>").attr("value",300).text("New 3"));
});
$("#dropdown").change(function() {
alert($(this).val());
});
});
</script>
<body>
<selec开发者_如何学Got id="dropdown"><option value="1">Old 1</option></select>
Because New1 is selected by default. If you select a selected option that doesn't qualify as a change.
Try this:
$("#dropdown").live('change',function() {
alert($(this).val());
});
on mousedown event, you actually regenerate the options, so the first child get selected. instead, you can try add empty option as default selected like this :
$(this).append($("<option></option>").attr("value",'').text("Select"));
$(this).append($("<option></option>").attr("value",100).text("New 1"));
$(this).append($("<option></option>").attr("value",200).text("New 2"));
......
精彩评论