Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove an element that is added dynamically in Javascript

I have the following code to create some element:

<div id="parent">
    <div id="block_1" >
        <div>
          <input type="text">
        </div>
        <img src="arrow.jpg">
        <div>
          <input type="text">
        </div>
        <div><a href="#" class="remove_block">Remove</a></div>
    </div>
</div>

the result look like this:

enter image description here

When user presses the ADD button it will go to a Javascript function and create the same block of div. Here is the code:

function add_block() {
var curDiv = $('#parent');
var i = $('#parent div').size()/4 + 1;
var newDiv='<div id="block_'+ i + '" class="parent_div">' +
'<div>' +
'<input type="text">' +
'</div>' +
'<img src="arrow.jpg">' +
'<div>' +
'<input type="text">' +
'</div><div><a class="remove_block" href="#">Remove</a></div>' +
'</div>';
$(newDiv).appendTo(curDiv);
};

Whenever the user press the "Remove" link on the left hand side of the block, that corresponding block should be removed. And this is what I did:

$('a.remove_block').on('click',function(events){
   $(this).parents('div').eq(1).remove();
});

The problem is that only the remove in the original block work, the rest didn't . Anybody know why?

enter image description here

I am new to jQuery and Javascript, so I really appreciate any help and suggestion Note: I use jQuery 2.0.3

like image 258
Nexus Avatar asked Oct 02 '13 04:10

Nexus


2 Answers

Because it's dynamic content, you can't bind events like the static content, it will not bind to the elements because they don't appear at the time you bind.

So you should bind event like this:

$('#parent').on('click', 'a.remove_block', function(events){
   $(this).parents('div').eq(1).remove();
});
like image 124
Chokchai Avatar answered Oct 08 '22 02:10

Chokchai


You need to use event delegation for dynamically added elements. Even though you have used .on() the syntax used does not use event delegation.

When you register a normal event it adds the handler to only those elements which exists in the dom at that point of time, but when uses event delegation the handler is registered to a element which exists at the time of execution and the passed selector is evaluated when the event is bubbled upto the element

$(document).on('click', '.remove_block', function(events){
   $(this).parents('div').eq(1).remove();
});
like image 38
Arun P Johny Avatar answered Oct 08 '22 02:10

Arun P Johny