vizon
vizon

Reputation: 363

Remove HTML that was added by AJAX

I have a page where I build orders. The page fully works with ajax to find products and add them to the page.

Now, if you add an item and need to remove it, I was building functionality to do so:

$('.orderRemove').click(function() {
    var removeID = $(this).attr("id");
    $("#item-" + removeID).remove();
    calculateTotal();
});

But since .orderRemove is added by AJAX it doesn't work.

How do I go about making this exact call work, removing the full block that was added by ajax.

Thank you

Upvotes: 1

Views: 104

Answers (2)

Daisy
Daisy

Reputation: 66

The reason is dynamically added HTML to the DOM does not attach itself to the event handlers so either re-attach the event handler in the ajax success call back or try .delegate if you are using jQuery version less than 1.7 or .on if you are using jQuery version 1.7 or higher

$(document).delegate('.orderRemove','click',function() {
    var removeID = $(this).attr("id");
    $("#item-" + removeID).remove();
    calculateTotal();
});

example with .on

$(document).on('click','.orderRemove',function() {
   var removeID = $(this).attr("id");
   $("#item-" + removeID).remove();
  calculateTotal();
});

Upvotes: 5

YogeshWaran
YogeshWaran

Reputation: 2281

You have to use on like this

$(document).on('click','.orderRemove',function() {
   var removeID = $(this).attr("id");
   $("#item-" + removeID).remove();
  calculateTotal();
});

Upvotes: 2

Related Questions