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

Answers:

Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.