Home > Web Front-end > JS Tutorial > Why Doesn't My jQuery `on('change')` Work on Dynamically Added Dropdowns?

Why Doesn't My jQuery `on('change')` Work on Dynamically Added Dropdowns?

Barbara Streisand
Release: 2024-12-15 13:43:12
Original
377 people have browsed it

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());
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template