views:

94

answers:

3

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>
<select id="dropdown"><option value="1">Old 1</option></select>
A: 

Try this:

   $("#dropdown").live('change',function() {
      alert($(this).val());
   });     
Sarfraz
+2  A: 

Because New1 is selected by default. If you select a selected option that doesn't qualify as a change.

Ben
A: 

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"));
......
Puaka
I would add .attr("disabled", true) to the "Select" option.
Ben