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
Try to use event-delegation
at this context,
$("#dftenglist").on("click", ".minusbtn", function() {
$(this).parent().remove();
});
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With