JQuery: cannot delete element dynamically created

I'm trying to remove a dynamically added element, but it seems that the class function attached to that element is not readable.

I can click the + button and add new items, but when I click the "-" button, I cannot delete.

<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

+3


source to share


1 answer


Try to use event-delegation

in this context,

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

      

DEMO

Why, you might ask? The reason is that when an event is registered for that particular element, that element will not be available in the DOM since we add it at runtime. Therefore, in this case event-delegation

, the concept of event bubbles under the hood will be used to overcome this problem. For more information read here .



For your new requirement just do as below, delete <br>

by deleting the parent.

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

      

DEMO

+3


source







All Articles