Motive
Motive

Reputation: 3111

jQuery Event on Dynamically added element not firing

I've been searching for how to do this and I've seen a lot of options (most of which are deprecated), but nothing I've tried has worked.

I have a file upload script that dynamically adds table rows and one <td> has some <button> elements that I need to do some Ajax work on click, but I can't seem to make it do anything.

Here's the <td>that contains the button that gets added to the DOM:

<td class="filedelete">
    <button class="btn btn-danger delete">
        <i class="icon-trash icon-white"></i> Delete
    </button>
</td>

This is the jQuery I am trying now:

$(".delete").on("click", function(event){
    console.log("clicked");
});

Is .on what I should be using? What am I doing wrong?

Upvotes: 1

Views: 349

Answers (1)

Colin Brock
Colin Brock

Reputation: 21565

Modify your code so that the event handler is bound to a containing element (maybe the parent <table> or another containing element that is static) like this:

$("#containing_element").on("click", ".delete", function(event){
    console.log("clicked");
});

The click event triggered from .delete will then bubble up and be caught by the containing element.

Upvotes: 2

Related Questions