Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery : Can't remove element dynamically created [duplicate]

I'm trying to remove a dynamically appended element, but it seems that the class function attached for this element is not read.

I can click on + button and add new elements, but I can't delete when clicking on "-" button.

<div id="dftenglist">
     <label for="dtfeng">Name:</label><input type="text" class="dfteng"> 
      <button id="plusdfteng">+</button> 
</div>

$("#plusdfteng").click(function() {
  $("#dftenglist").append('<br><span><label for "a">Name:</label><input type="text" class="dfteng"> <button class="minusbtn">-</button></span>'); 
});

$(".minusbtn").click(function() {
  $(this).parent().remove();
})

http://jsfiddle.net/0uv4k5bz/1/

Thanks, Alex

like image 539
Alex Palombo Avatar asked Oct 08 '14 11:10

Alex Palombo


1 Answers

Try to use event-delegation at this context,

$("#dftenglist").on("click", ".minusbtn", function() {
  $(this).parent().remove();
});

DEMO

You may ask why? The reason is, while registering event to that particular element, that element will not be available at the DOM since we are adding it at the runtime. So at that case event-delegation will make use of the event-bubbling concept under the hood to over come this issue. For more info read here.

For your new requirement just do like below, remove the <br> while removing the parent element.

$("#dftenglist").on("click", ".minusbtn", function () {
    $(this).parent().prev('br').addBack().remove();
});

DEMO

like image 129
Rajaprabhu Aravindasamy Avatar answered Oct 16 '22 04:10

Rajaprabhu Aravindasamy