Why is my jquery .on('change') not working for dynamically added selects

Your code:

$('#x select').on('change', function () { alert('helo'); })

attaches an event handler to the select inside the #x element.

What you want (from what i understood) is something in the lines of:

$("#y").on('change','select',function () { alert('helo'); });

This attaches an event handler to the #y element that gets delegated to its children 'select' elements

From http://api.jquery.com/on/

The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.


Event binding to elements that are not in the DOM on initial page load will not work. You need to bind to an element further up the DOM that exists to allow the event to trickle down. This is usually the approach that I take:

$(document).on({
  change: function() {
    alert('helo');
  }
}, '#x select');

$(document).on({
  change: function() {
    alert('helo');
  }
}, '#y select');

I prefer it as you can add subsequent events easily.

$(document).on({
  change: function() {
    alert('helo');
  },
  blur: function() {
    alert('helo');
  }
}, '#x select');

Don't use .live()/.bind()/.delegate(), though. You should use .on().

for both static and dynamic select changes

$(document).on('change', 'select', function (e) {
    // do something 
});

Tags:

Jquery