5

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

codingrose
  • 15,563
  • 11
  • 39
  • 58
Alex Palombo
  • 135
  • 1
  • 2
  • 8

1 Answers1

9

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

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • This works, thanks! but to be perfect , how can I make the other objects shift up? For example , I click "+" 3 times. So if I click "-" on the first new object created, I want to the other elements shift up. – Alex Palombo Oct 08 '14 at 11:47
  • @AlexPalombo Ok i am making a demo for that just wait, before that since you are new to Stackoverflow, i just want to tell some of the guidelines being followed here. That is, if you find any one of the answers provided for your question has satisfied your need, then try to accept it by clicking on the tick mark available with that particular answer. And purely it is not a compulsion... :) :) – Rajaprabhu Aravindasamy Oct 08 '14 at 11:52
  • got it, just add
    inside the
    – Alex Palombo Oct 08 '14 at 11:53
  • @AlexPalombo Oh.. that's a nice move, though you can use my solution too.. see the updated answer.. – Rajaprabhu Aravindasamy Oct 08 '14 at 11:53