Attach event to dinamically added HTML elements with jQuery

If you have an event handler defined like this in JavaScript:

$("a[product-id]").click(edit_product);

function edit_product(event) {
    ...
}

After adding elements (nodes) dinamically (after an AJAX call for example) that fit that selector to the HTML DOM with .append() or .html(), the event won’t work on them. That’s because the element was added AFTER calling the event method that links to the function we want to execute.

To ensure all elements that fit the selector will trigger the event you have to use .on() for example with $(document) as the ancestor:

$(document).on('click', "a[product-id]", edit_product);

jquery-logo

Ref: http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements

You might also like

Create a bootable Ubuntu USB drive from an ISO in Ubuntu
The first thing we need to do is download an Ubuntu ISO file. The second one is plugin the USB drive...

Symfony Forms and Bootstrap Datetimepicker
In this example I'm going to use the spanish locale and the "Europe/Madrid" timezone.First we need...

Fix “This field was locked by vendor” in Plesk Updates source and installation settings
I was trying to install some new components to one on my Plesk managed servers but I got this error when...

Adding PHP 7.0 support in Plesk
First thing you need to do is update to Plesk 12.5 (currently 12.5.30). For that you have to go to Server...

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.