I created a clearPage() function to override window.location.reload() , it works fine with one product type in cart, but if I add 2nd type (another couch) the 2nd one works fine (change of price and quantity), but the first, the price cannot be calculated (with quantity everything is fine). Can anyone help me to solve this problem. Please. Thanks.
async function showCart() {
if (basketStr == null) {
let createpEmpty = document.createElement('p')
createpEmpty.textContent = 'Votre panier est vide'
cartPanel.appendChild(createpEmpty)
} else {
let totalPrice = 0
for (let i = 0 ; i < basket.products.length; i++) {
basketProduct = basket.products[i]
showProductBasket(basketProduct)
let productsPrice = await getProduct(basketProduct.id)
let productQuantity = basketProduct.quantity
totalPrice += productsPrice.price * productQuantity
let totalPriceElt = document.querySelector('#totalPrice')
totalPriceElt.textContent = totalPrice
}
let totalQuantity = document.querySelector('#totalQuantity')
totalQuantity.textContent = basket.totalQuantity
changeQuantity()
delProduct()
}
}
showCart()
// Changement quantité et prix
function changeQuantity() {
let quantityItem = document.querySelectorAll('.itemQuantity')
for (let k = 0; k < quantityItem.length; k++) {
quantityItemUnit = quantityItem[k]
quantityItemUnit.addEventListener('change', function(event) {
for (let l = 0 ; l < basket.products.length; l++) {
basketProduct = basket.products[l]
let articleQuantityItemID = event.target.closest('article').getAttribute("data-id")
let articleQuantityItemColor = event.target.closest('article').getAttribute("data-color")
newQuantityValue = event.target.valueAsNumber
if (basketProduct.id == articleQuantityItemID && basketProduct.color == articleQuantityItemColor) {
qtyToAdd = newQuantityValue - basketProduct.quantity
basketProduct.quantity = newQuantityValue
basket.totalQuantity = basket.totalQuantity + qtyToAdd
// JSON.stringify() method converts a JavaScript value to a JSON string
let lineBasket = JSON.stringify(basket)
localStorage.setItem("basket", lineBasket)
clearPage()
showCart()
}
}
})
}
}
function clearPage() {
let cartPr = document.getElementById("totalPrice")
let cartQuan = document.getElementById("totalQuantity")
let cartItems = document.getElementById("cart__items")
cartPr.innerText = ''
cartQuan.innerText = ''
cartItems.replaceChildren()
}