Question

I need some help in jQuery with ".remove". I create new "tr" in a table with ".append"

$("#myinput").keypress(function(e){
    if(e.keyCode==13){
        $('#mytable tbody:last').append("<tr><td></td><td><a id='delete' href='' >X</a></td></tr>");
        return false;
    }
});

When I add many "tr" and I try to delete one of them, it's delete all "tr".

$("#mytable #delete").on("click",function() {
    $(this).closest("tr").remove();
    return false;               
});

What I can do? Thank you :)

Was it helpful?

Solution

You need event delegation for dynamically added elements. The time the event binding code executes the tr is not present and using event delegation will bind the event when tr is added.

$("#mytable").on("click", "#delete", function() {
    $(this).closest("tr").remove();
    return false;               
});

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers, jQuery doc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top