durje
durje

Reputation: 135

Detect a user change of a <select> list created with Jquery ".html()"

Is there a way to detect when the value of a select list is changed, when this select list have been added with the .html(htmlString) or .append(content[,content]) jQuery function?

HTML CODE:

<ul class="htmlClass">
   <!-- Populated via JS -->
</ul>

JAVASCRIPT CODE:

var MyDropDownMenu= "";
MyDropDownMenu += '<select class="field">';
MyDropDownMenu += '<option value="1">Option 1</option>';
MyDropDownMenu += '<option value="2">Option 2</option>';
MyDropDownMenu += '</select>';
$('ul.htmlClass').html(MyDropDownMenu);

$(".field").change( function() {   //Doesn't work!!!
      alert("test1");
});

$(".htmlClass").change( function() {  //work        
      alert("test2");
});

Upvotes: 3

Views: 2043

Answers (2)

Claudio Redi
Claudio Redi

Reputation: 68400

Use delegated event handlers

$('ul.htmlClass').on('change','.field', function() {
  alert("test1"); 
});

See Direct and delegated events for more information.

Another problem in your code is that you're adding your select directly to the ul element. This is not correct.

I see two options

1) wrap select with a li tag

var MyDropDownMenu= "<li>";
myDropDownMenu += '<select class="field">';
MyDropDownMenu += '<option value="1">Option 1</option>';
MyDropDownMenu += '<option value="2">Option 2</option>';
MyDropDownMenu += '</select>';
MyDropDownMenu += '</li>';

2) Convert your ul to a div if you don't require a list

Upvotes: 4

Adil Shaikh
Adil Shaikh

Reputation: 44740

You need to use event delegation

$('ul.htmlClass').on('change',".field", function() { 
      alert("test1");
});

Upvotes: 6

Related Questions