Price calculation by product quantity in shopping cart

44 Views Asked by At

I have a problem with my calculation by product quantity function. The checkout calculation function works perfectly. Increasing the quantity of one product and including its price also works great, but if I have more products and increases the quantity of the first product from the list, the console counts all the products below.

In the last photo below, the result of clicking + on the first product on the list.

let totalPrice = 0;

// Add to cart function
const addCartBtn = section => {
  let cartBtn = document.querySelectorAll(section);
  cartBtn.forEach(btn => {
    btn.addEventListener("click", () => {
      const price = btn.parentElement.parentElement.children[3].children[0];

      let cart = document.querySelector('.cart .items');

      let item = document.createElement("div");
      item.innerHTML = 
      `
          <div class="price-info">
              <div class="price">${price.textContent}</div>
          </div>
          <div class="quantity">
              <div class="minus">-</div>
              <div class="number">1</div>
              <div class="plus">+</div>
          </div>
      `

    // Changing item's quantity
    itemQuantitySystem(price);

    // Checkout calculation
    checkoutCalculation(price);

})
})}

// Checkout calculation function
const checkoutCalculation = priceCalc => {
  priceCalc = parseFloat(priceCalc.textContent);
  totalPrice += priceCalc;
}

// Checkout calculation by quantity
const checkoutQuantity = (priceCalc, quantity) => {
  priceCalc = parseFloat(priceCalc.textContent);
  priceCalc *= quantity;
  totalPrice += priceCalc;
}

// Quantity system
const itemQuantitySystem = (priceCalc) => {
  for (const systemElement of document.querySelectorAll(".quantity")) {
    const number = systemElement.querySelector(".number");
    const minus = systemElement.querySelector(".minus");
    const plus = systemElement.querySelector(".plus");
    
    let quantity = parseInt(number.textContent);
  
    plus.addEventListener("click", () => {
      quantity++;
      number.textContent = quantity;
      checkoutQuantity(priceCalc, quantity)
    })
  }
}

0

There are 0 best solutions below