(Please excuse the nested ifs, just learning this stuff as I go along)
Below is the code that's not working, the if and else, in the for/in loop, both run.
function checkCart(product) {
if (cart.length == 0) {
cart.push(product);
addItemToCart(product);
} else {
for (let item in cart) {
if (cart[item].productName == product.productName) {
product.quantity += 1;
updateCartQuantity(product);
} else {
cart.push(product);
addItemToCart(product);
}
}
}
}
Full code:
let cart = [];
let cartTotal = 0;
let cartAmountItems = 0;
let productsArr = [
{
productName: "Blender",
productPrice: 1699,
src: "./images/blender.jpg",
quantity: 1,
},
{
productName: "Xbox",
productPrice: 9000,
src: "./images/xbox.jpg",
quantity: 1
},
{
productName: "Chair",
productPrice: 800,
src: "./images/chair.jpg",
quantity: 1
},
{
productName: "Microwave",
productPrice: 1800,
src: "./images/microwave.jpg",
quantity: 1
},
{
productName: "Table",
productPrice: 900,
src: "./images/table.jpg",
quantity: 1
},
{
productName: "TV",
productPrice: 18000,
src: "./images/tv.jpg",
quantity: 1
},
]
let itemsDiv = document.querySelector("#items");
for (const product of productsArr) {
itemsDiv.innerHTML += `
<div class="productItem">
<img src="${product.src}" class="productImage">
<span class="productName">${product.productName}</span>
<hr>
<span class="productPrice">R${product.productPrice}</span>
<button class="addToCart">Add to cart</button>
</div>
`
}
let addToCartBtn = document.getElementsByClassName("addToCart");
for (let x = 0; x < addToCartBtn.length; x++) {
addToCartBtn[x].addEventListener('click', event => {
let item = event.path[1].childNodes[3].innerHTML;
for (const product of productsArr) {
if (product.productName == item) {
checkCart(product);
addToTotal(product);
addToCartAmount();
}
}
});
}
function checkCart(product) {
if (cart.length == 0) {
cart.push(product);
addItemToCart(product);
} else {
for (let item in cart) {
if (cart[item].productName == product.productName) {
product.quantity += 1;
updateCartQuantity(product);
} else {
cart.push(product);
addItemToCart(product);
}
}
}
}
function updateQuantity(product) {
for (let item in cart) {
if (cart[item].productName == product.productName) {
product.quantity += 1;
}
}
}
function addToTotal(product) {
cartTotal += product.productPrice;
document.getElementById('cartTotal').innerHTML = cartTotal;
}
function addToCartAmount() {
cartAmountItems = cartAmountItems + 1
document.getElementById('cartAmountItems').innerHTML = cartAmountItems;
}
function addItemToCart(product) {
document.getElementById('cart').innerHTML +=
`<div class="newItem">
<img src="${product.src}" alt="${product.productName}">
<p>${product.productName}</p>
<p>R ${product.productPrice}</p>
<p id="${product.productName}-Quantity">${product.quantity}</p>
</div>`
}
function updateCartQuantity(product) {
document.getElementById(`${product.productName}-Quantity`).innerHTML = product.quantity;
}
Thank you for any help.
Aucun commentaire:
Enregistrer un commentaire