Problem with calculating the total price in shopping cart

61 views Asked by At

I have trouble calculating the total price after adding products to the cart. Instead of adding numbers, the variable adds characters to create a string.

Add to cart function in Vanilla JS:

const addCartBtn = (section) => {
  let totalPrice = 0;
  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.classList.add("item");
      item.innerHTML = 
      `
          <div class="price-info">
              <div class="price">${price.textContent}</div>
          </div>
      `

    cart.appendChild(item);

    // Checkout calculation
    let totalPriceDiv = document.querySelector(".total-price");
    let priceCalc = parseFloat(price.textContent).toFixed(2);
    totalPrice += priceCalc;
    totalPriceDiv.innerHTML = totalPrice;

})
})}

Result Result on the page

I tried creating the totalPrice variable as an empty string, array, but each time the variable creates a string instead of adding the numbers to itself.

Thanks for the help in advance

1

There are 1 answers

0
mrstronk On

You can deal with the numbers as digits by converting the price to a floating-point number

// Convert the price to a floating-point number
let priceValue = parseFloat(price.textContent);

      item.innerHTML = 
      `
          <div class="price-info">
              <div class="price">${priceValue.toFixed(2)}</div>
          </div>
      `;

      cart.appendChild(item);

      // Checkout calculation
      let totalPriceDiv = document.querySelector(".total-price");
      totalPrice += priceValue;
      totalPriceDiv.innerHTML = totalPrice.toFixed(2);
    });
  });
};