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

jQuery Migration: Why Doesn't `on()` Work With Dynamically Added Dropdowns?

Barbara Streisand
Release: 2024-12-08 16:40:11
Original
825 people have browsed it

jQuery Migration: Why Doesn't `on()` Work With Dynamically Added Dropdowns?

jQuery: Upgrading from live() to on() for Dynamically Added Dropdowns

jQuery 1.7 introduced the on() method as a replacement for live(). While the syntax and intended functionality of on() appear straightforward, users may encounter issues when attempting to migrate from live() to on() for dynamically added elements.

Problem:

When using on() to listen for change() events on dynamically added dropdown menus, the event handler fails to fire.

Cause:

Unlike live(), which attached event handlers to all matching elements in the document, on() only binds handlers to existing elements. This is because on() event handlers are confined to the currently selected elements, which means that newly added elements will not be able to trigger the event unless the handler is bound to a higher-level element.

Solution:

To replicate the behavior of live(), bind the event handler to a higher-level element that encapsulates the dynamically added dropdowns. This ensures that all newly added elements within that scope will be able to trigger the event handler.

Code:

$(document.body).on('change', 'select[name^="income_type_"]', function() {
    alert($(this).val());
});
Copy after login

Alternatively, it is best practice to bind the event handler as close as possible to the target elements. However, this may not always be feasible in all scenarios.

Note:

It's important to be aware that the on() documentation explicitly states that event handlers are only bound to currently selected elements and must exist on the page at the time of binding.

The above is the detailed content of jQuery Migration: Why Doesn't `on()` Work With 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