Home >Web Front-end >JS Tutorial >Why Doesn't My jQuery `on('change')` Work on Dynamically Added Dropdowns?
Transitioning jQuery's live() to on(): What Went Wrong?
In jQuery, the live() method has been replaced by on() for event handling. However, despite migrating to jQuery 1.7 and using on('change') to detect changes in dynamically added Dropdowns, the event handler remained inactive.
The Solution
The key difference lies in the way on() handles event delegation. Unlike live(), which attaches event handlers to dynamically created elements, on() binds handlers only to elements that exist at the time of its invocation.
To achieve the same functionality as live(), the on() syntax should be modified as follows:
$(document.body).on('change', 'select[name^="income_type_"]', function() { alert($(this).val()); });
This binds the event handler to the document body, which ensures that handlers are attached even for elements added dynamically.
Alternatively, for more targeted event handling, consider attaching handlers to the closest possible ancestor element.
The jQuery documentation explicitly states that on() behaves differently from its predecessors, emphasizing that event handlers are bound only to existing elements. This explains why the initial implementation with on('change') was not firing.
The above is the detailed content of Why Doesn't My jQuery `on('change')` Work on Dynamically Added Dropdowns?. For more information, please follow other related articles on the PHP Chinese website!