Increasing quantity of product thats already in cart doesnt work

19 Views Asked by At

I am trying to increase quantity of a product that's already in a cart in a way of summing up value representing amount that customer wants to add and quantity value that's already in cart object, but my output is 1+2=12 instead of 1+2=3.

const products = [
    {
        id: "ryuliachaeTshirt",
        name: 'RYULIACHAE T-Shirt',
        priceCents: 25 + ' Eur',
        quantity: 1
        
        

    }
];
   
const plus = document.querySelector(".plus"),
    minus = document.querySelector(".minus"),
    num = document.querySelector(".num");

    var a = 1;
    plus.addEventListener("click", ()=> {
        a++;
        num.innerHTML = a;
       // console.log(a)
    });
    minus.addEventListener("click",()=> {
        if (a < 2) {
            num.innerHTML = 1;
        } else {
            a--;
            num.innerHTML = a;
         //   console.log(a)
        }
    });


document.querySelectorAll('.AddToCart')
    .forEach((button) => {
        button.addEventListener('click', () => {
            const productId =button.dataset.productId;
            var quantity = document.querySelector('.num').innerHTML;
            //console.log(quantity)
            let matchingItem;
            cart.forEach((item) => {
                if (productId === item.productId) {
                    matchingItem = item;
                }
            })
            if (matchingItem) {
                var finalQuanity = matchingItem.quantity + quantity
                matchingItem.quantity = finalQuanity;
            } else {
                cart.push({
                    productId: productId,
                    quantity: quantity
                });
            }
            console.log(cart);
        });
    })

I've tried looking where could be some kind of mistake I did, played with the values I am adding up, tried putting it into function before assigning the final value and nothing worked, now I am kinda lost.

0

There are 0 best solutions below