Reputation:
I need to count total price of all products, which are added to my shopping cart. Instead it displays total price of all products and the price of one product, which was added, one on another. I can't fix it. I'll add the piece of my code:
JS:
// CART:
let cart = (JSON.parse(localStorage.getItem(".cart")) || []);
const cartDOM = document.querySelector(".cart");
const addToCartButtonsDOM = document.querySelectorAll('[data-action="ADD_TO_CART"]');
const deleteNoItemsInTheCart = document.getElementById("delete");
const itemsDOM = document.querySelector(".items");
const prices0Dom = document.querySelector(".pricesDom");
const totalPrice = document.getElementById("total");
const totalPriceDom = document.querySelector(".total1");
// add to cart:
addToCartButtonsDOM.forEach(addToCartButtonDOM => {
addToCartButtonDOM.addEventListener("click", () => {
const productDOM = addToCartButtonDOM.parentNode;
const product = {
name: productDOM.querySelector("#product__name").innerText,
price: productDOM.querySelector("#product__price").innerText,
quantity: 1,
};
const isInCart = (cart.filter(cartItem => (cartItem.name === product.name)).length > 0);
if (!isInCart) {
insertItemToDOM(product);
cart.push(product);
localStorage.setItem("cart", JSON.stringify(cart));
addToCartButtonDOM.innerText = "In Cart";
deleteNoItemsInTheCart.remove();
totalPriceDom1();
}
});
});
// display items, which were added to cart, in a basket message:
function insertItemToDOM(product) {
cartDOM.insertAdjacentHTML("beforeend", `<div class="cartDOM"><br>
<p>${product.name}<br>${product.price}</p></div>`);
}
// delete all:
function deleteAllButton() {
cartDOM.remove();
itemsDOM.insertAdjacentHTML("beforeend", `<p class="noItems">No
items in the cart</p>`);
totalPriceDom.remove();
prices0Dom.insertAdjacentHTML("beforeend", `<p class="prices0Dom">Total price: 0$</p>`);
}
// calculate total price
function calculateTotalPrice() {
return cart.reduce((acc, cartItem) => {
const price = parseInt(cartItem.price.slice(0, cartItem.price.length - 1));
const quantity = cartItem.quantity;
return acc + price * quantity;
}, 0);
}
// display total price in a basket message:
function totalPriceDom1() {
totalPrice.remove();
const total = calculateTotalPrice(); // new code
totalPriceDom.insertAdjacentHTML("beforeend", `<p class="totalPrice">Total price: ${total}$</p>`);
}
https://codepen.io/tatarusetskaya/pen/XWpzNZa
Upvotes: 0
Views: 1692
Reputation: 787
Just replace 110 line:
totalPriceDom.insertAdjacentHTML("beforeend", `<p class="totalPrice">Total price: ${total}$</p>`);
with:
totalPriceDom.innerHTML = `<p class="totalPrice">Total price: ${total}$</p>`;
If you don't want to use innerHTML, then use
while (totalPriceDom.firstChild) {
totalPriceDom.firstChild.remove();
}
totalPriceDom.insertAdjacentHTML("beforeend", `<p class="totalPrice">Total price: ${total}$</p>`);
Upvotes: 1