Zinox
Zinox

Reputation: 535

jQuery remove selected element, dynamically generated

I have a form and I can dynamically add more lines but if I try to remove a specific line it does not work, however the first line gets removed with no problem.

Here is the html:

<form class="order-form">
  <div class="product-lines">
<!-- Product Line Section -->
  <div class="product-line">                
<a href="#" alt="close" class="btn-close" title="Remove"><img alt="remove" src="img/close.png"  /></a>
<input class="input-text" name="product-code" type="text" placeholder="Product Code" ></input>
<input class="input-text" name="product-quantity" type="text" placeholder="Quantity"></input>
<input class="input-text" name="product-discript" type="text" placeholder="Discription of Product"></input>
<label class="label-sign">&pound;</label>
<input class="input-text" name="product-price" type="text" placeholder="RRP Price"></input>
<br>
  </div>
</div>

<div id="product-btn">                  
<input name="btn-add-line" type="button" value="Add new line"></input>
<input name="btn-update" type="button" value="Update"></input>
<input name="btn-submit" type="submit" value="Submit Order"></input>
<label class="label-sign">&pound;</label>
<input class="input-text" name="order-info" type="text" placeholder="Order total" ></input>
</div>                  
</form>

The jQuery code I have tried:

$(".btn-close").on("click", function(e){
    $(e.currentTarget).parent().remove();   
}); 

I've also Tried

$(e.currentTarget).parents("div.product-lines).next("div.product-line).remove();

Any help would be most appreciated, also a explanation would be very helpful for me to learn.

Upvotes: 0

Views: 1782

Answers (3)

elrado
elrado

Reputation: 5272

Try something like

$(".product-lines").on("click", ".btn-close", function(e){

    $(e.currentTarget).parent().remove();   

});

You cannot attach events to objects that are not currently on page (lines). You have to attach click event on product-lines object and when it is clicked you delegate event to "closest" product-line object!

Upvotes: 3

Sachin
Sachin

Reputation: 582

$('body').on('click','button id/class',function(){

$(e.currentTarget).parent().remove(); 
});

but if u use this code it will remove <div class="product-line">...</div>

why you want to remove this div.

i dont get your question very well. Explain in details and step by step .

Upvotes: 1

haxtbh
haxtbh

Reputation: 3534

You will need to changed the jQuery slightly to allow for Event Delegation. This means all elements added in future will get the event attached to them too.

$(document).on("click", ".btn-close", function(e){

   $(e.currentTarget).parent().remove();   

}); 

Upvotes: 1

Related Questions