Skip to content Skip to sidebar Skip to footer

Unable To Remove Dynamically Added Content With Jquery

I'm using jQuery to let users dynamically add and remove form fields, but it's not working properly. It works perfectly fine when removing the first field (which is hard-coded in t

Solution 1:

Here's how you want to use on

$(document).on("click", ".deleteDog", function(e) {
    e.preventDefault();
    $(this).parent().remove();
});

Ideally all of these deleteDog buttons will be housed in some sort of container. If all of these buttons were to be in a div with an id of foo, you would more efficiently set up the events like this:

$("#foo").on("click", ".deleteDog", function(e) {
    e.preventDefault();
    $(this).parent().remove();
});

Now, instead of every click anywhere in the document being inspected, only those clicks that bubble up to #foo are.


I'm guessing you originally tried to use on like this:

$(".deleteDog").on("click", function(e) {
    e.preventDefault();
    $(this).parent().remove();
});

This is functionally identical to saying:

$(".deleteDog").bind("click", function(e) {
    e.preventDefault();
    $(this).parent().remove();
});

Omitting the selector parameter like this creates a directly-bound event—only the elements that match the .deleteDog selector at the time on is called will be wired.

Applying a selector—like in my original code—makes it a delegated event—jQuery will listen for all clicks, and if they originate from an element with the class deleteDog, the function will fire.

Post a Comment for "Unable To Remove Dynamically Added Content With Jquery"