0

I am dynamically creating list items in shopping cart. I have to get remove items' button's sibling's children values like quantity and price while removing a cart item but method is not working.

var cartItem= $("<li class='newItem'>
    <p class='id'>"+id+"</p>
    <div class='picture'><img src='"+ image +"' ></div>
    <div class='details'>
        <span class='weight'>"+weight+"<span> /</span>
        <span class='avail'>"+availability+"</span> 
        <p class='price'>"+price+"</p> 
        <p class='name'>"+name+"<p class='quantity'>"+quantity+"</p>
    </div> 
    <a type='button' class='removeItem'>Remove Item</a>
</li>");

$("#cartList").prepend(cartItem); //creating list item

//Remove a Cart Item
$(".removeItem").click(function(){
    $(this).parent().remove();

    //Show empty cart view if all items are removed
    if( ($("#cartList").has("li").length === 0) ) {
        $("#empty-cart").css("display","block");
        $("#shipping_text, #total_amount_text").css("display", "none");
    }

    //Decrement in total amount while removing an item
    var q = parseInt($(this).siblings('.details').children('.quantity').text());
    var p =parseInt($(this).siblings('.details').children('.price').text().replace("$", ""));
    console.log($(this).siblings('.details'));
    total -= q*p;
     
    $("#total_amount_text span").text(total)
})
Don't Panic
  • 13,965
  • 5
  • 32
  • 51
  • Selectors and event handlers specified at page load will only match elements which exist at page load. You are adding new elements *after* page load, and your event listeners (`$(".removeItem").click()`) will not match them - jQuery doesn't know about those new elements. You need to delegate your handlers to an element that exists at load, and filter to match only your target elements. This is a very common problem, and there are many duplicates and variations here on SO, [here's one](https://stackoverflow.com/questions/1359018/how-do-i-attach-events-to-dynamic-html-elements-with-jquery). – Don't Panic Aug 21 '21 at 09:22
  • Does this answer your question? [How do I attach events to dynamic HTML elements with jQuery?](https://stackoverflow.com/questions/1359018/how-do-i-attach-events-to-dynamic-html-elements-with-jquery) – Don't Panic Aug 21 '21 at 09:22

0 Answers0