Inderjeet
Inderjeet

Reputation: 1528

Jquery: Closest() div remove not working

Jquery closest div remove not working i found same question on stackoverflow but these answered not resolve my problem

closest div remove js fiddle here

<script>
$(document).ready(function(){
    var counter = 4;
    var name = 1;
    var qty = 1;
    var price = 1;
    $('#addproduct').click(function() {
        $('#dynamicInput').append('<div class="clearfix"></div><div class="pdd" id="dlt"><div class="col-sm-3"><div class="row">' + (counter++)+' <label>Product Name</label></div></div><div class="col-sm-3"><div class="row"><select name="productnm'+(name++)+'"><option>Select Product</option><option>Rice</option><option>Fried Rice</option><option>Biryani</option></select></div></div><div class="col-sm-3"><div class="row"><label>Quantity</label></div></div><div class="col-sm-1 row"><div class="row qunatity-number"><input type="number" name="qunatity'+(qty++)+'" value="1" /></div></div><div class="col-sm-2"><div class="row qunatity-totalprice"><input type="text" name="totalprice'+(price++)+'" placeholder="Total Price" disabled /></div></div><a class="deleter" ><i class="fa fa-trash-o" aria-hidden="true"></i></a></div> ');
    });
    $('.deleter').click(function(){
       $(this).closest("#dlt").remove();
     });

});

</script>

Upvotes: 2

Views: 3947

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76717

You add a click event to the deleter before it is created, since it is created on click to addproduct, which did not happen when the document is loaded. You will need to create an on event, like this:

$('#dynamicInput').on("click", ".deleter", function() {
    $(this).parent().remove();
});

You also need to make sure you do not duplicate HTML ids. It is an incorrect way of HTML programming. When something is unique, use an id. When it is not unique, use a class.

Upvotes: 1

ad_on_is
ad_on_is

Reputation: 1550

Since you add your elements afterwards to the dom, the click-event is not bound to your .deleter. you have to invoke it every time you create a new element like this: https://jsfiddle.net/woeot0L4/5/

Upvotes: 0

Shiladitya
Shiladitya

Reputation: 12181

Here is the solution for you https://jsfiddle.net/woeot0L4/1/

$(document).on('click', '.deleter',function(){
   $(this).parent().remove();
});

Since you are appending the deleter class element dynamically, click will not work. Either you need to bind an event to the class or use document on click.

Upvotes: 3

Related Questions