user10768139
user10768139

Reputation:

How can I remove an item from this cart?

I have created this cart by watching lots and lots of tutorials. Now I have come to remove an item from the cart. I would really appreciate if some one could help me out.

//add item to cart

(function(){
    const cartbtn = document.querySelectorAll(".add_to_cart_button");

    cartbtn.forEach(function(btn) {
        btn.addEventListener("click", function(event){
            if (event.target.parentElement.classList.contains("add_to_cart_button"))
            {
        let fullpath = event.target.parentElement.previousElementSibling.children[0].children[0].src;
                const item = {};
                item.img =  fullpath;
        let name = event.target.parentElement.previousElementSibling.children[3].children[0].textContent;
                item.name = name;
        let price =  event.target.parentElement.previousElementSibling.children[3].children[1].textContent;
        let finalprice = price.slice(1).trim( );       
                item.price = finalprice;
            //console.log(item);
               const cartitem = document.createElement('li');
               cartitem.classList.add("clearfix");
               cartitem.innerHTML =
            `
                                      <img src="${item.img}" alt="item1" />
                                      <span class="item-name">${item.name}</span>
                                      <span class="item-price">${item.price}$</span>
                                      <span class="item-quantity"> <a href="#/" />Delete</span>

            `;
            const cart = document.getElementById("cartitem");
            const insert =document.querySelector("insert");
            cart.insertBefore(cartitem,insert);
                showtotal();

            }
            });
        });
        function showtotal(){
            const total =[];
            const items = document.querySelectorAll(".item-price");

            items.forEach(function(item){
                total.push(parseFloat(item.textContent));
            });
            const totalmoney=total.reduce(function(total,item){
                total += item;
                return total;
            },0);
            const finalmoney = totalmoney.toFixed(2);
            document.getElementById("totalitem").textContent=total.length;
            document.getElementById("totalitems").textContent=total.length;
            document.querySelector(".main-color-text").textContent = finalmoney ;
        }
})();

Upvotes: 2

Views: 233

Answers (1)

At the code line,

<a href="#/" />Delete</span> // Also, do not forget to close Anchor Link tags

You can add a class, to these Delete buttons,

<a href="#/" class="remove-item-from-cart">Delete</a>

Add an event to your remove-item-from-cart classes when the page is fully loaded and in the event listener, use some JavaScript to delete item from cart by checking event variable.

Upvotes: 1

Related Questions