user2847429
user2847429

Reputation:

Deleting a dynamically added div on a parent causes it to append again

JsFiddle

I am trying to dynamically add a div on clicking td.active. I wish to remove the dynamically added div when someone click on the close button or click on other td.active

Right now my code just append another div when the close button is clicked. can anyone help me to fix the issue.

$(function() {
    $('td.active').click(function(event){
        $(this).append('<div class="planner-modal"><div class="planner-modal-header"><button type="button" class="close"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button><h5 class="text-center">modal heading</h5></div><div class="planner-modal-body">modal body</div><div class="caret-container"><div class="top-caret"></div><div class="bottom-caret"></div></div></div>');
    });
    $('.planner-modal-header.close').click(function(e){
        $(this).closest('planner-modal').remove();
    });
});

Upvotes: 0

Views: 46

Answers (2)

Balachandran
Balachandran

Reputation: 9637

Use event delegation for dynamicaly created element

  $('td.active').on("click", ".planner-modal-header .close", function (e) {
    e.stopPropagation(); 
    $(this).closest('.planner-modal').remove();
});

DEMO

use e.stopPropagation(); to stop the bubbling event

Upvotes: 1

Devendra Soni
Devendra Soni

Reputation: 1934

I have gone through the jsfiddle and fixed it. you were trying to call click event on dynamically added content for ding this we can use jQuery on method. i am sharing the jsfiddle link.

  $(document).on("click",'.close',function(e){

      $('.planner-modal').remove()
    });

click here to see the working jsfiddle example

thanks

Upvotes: 2

Related Questions