Increases and decreases the quantity by 1

Good evening,

I added 2 + and - icons
<i class="fa-solid fa-plus fa-lg" id="addtocart${id}")></i>
<i class="fa-solid fa-minus fa-lg" id="addtocart${id}></i>")
and I don’t know how to make it so that when I click on the + it increases the quantity by 1 and on the - it decreases the quantity by 1?

Can you help me because I have been looking for two days how to solve this in the script.js file

Thank you for your help

import { products } from "./items";

// Toggle shopping cart
const shoppingCart = document.getElementById("shoppingCart");
const closeCart = document.getElementById("closeCart");

const itemContainer = document.getElementById('itemContainer');
const cartContainer = document.getElementById("cartContainer");
const eachCartItemContainer = document.getElementById("eachCartItemContainer");
const totalItem = document.getElementById("totalItem");

const cartTitle = document.getElementById("cartTitle")
const totalPrice = document.getElementById("totalPrice");
const totalPriceContainer = document.getElementById("totalPriceContainer");

const storedItems = localStorage.getItem("cartItems")
const cartItems = storedItems !== null
    ? storedItems.split(",")
    : []


totalItem.innerText = cartItems.length !== null
    ? cartItems.length - 1
    : 0

// Iterate card
for (let index = 0; index < products.length; index++) {
    const { id, productName, productPrice, productImg } = products[index]
    itemContainer.innerHTML +=
        ` <div class="card">` +
        ` <article class="cardImg">` +
        ` <img src="./img/${productImg}" alt="">` +
        `</article> ` +
        ` <div class="itemDescContainer">` +
        `<article class="itemDesc">` +
        `<h1 class="itemName">${productName}</h1>` +
        `<p class="itemPrice">${productPrice}€</p>` +
        ` </article> ` +
        `<div class="addtocart" id="addtocart${id}")'>` +
        `<i class="fa-solid fa-cart-shopping cart"></i>` +
        ` </div>` +
        ` </div>` +
        `</div>`
}

// Add click event listener for card Item
for (let index = 1; index <= products.length; index++) {
    document.getElementById(`addtocart${index}`).onclick = () => {
        if (cartItems.includes(index) === false) {
            totalItem.innerText = cartItems.length;
            cartItems.unshift(index)
            localStorage.setItem("cartItems", cartItems)
        }
    }
}

shoppingCart.onclick = () => {
    cartContainer.classList.add("showCartContainer");
    displayItemInCart();
}

closeCart.onclick = () => {
    cartContainer.classList.remove("showCartContainer");
}

// AddClickEvent for button
const displayItemInCart = () => {
    cartTitle.innerText = `${cartItems.length - 1} Item In cart`;
    eachCartItemContainer.innerHTML = "";
    if (localStorage.getItem("cartItems")) {
        const cartArray = localStorage.getItem("cartItems").split(",");
        totalPrice.innerText = "";
        totalPriceContainer.style.display = "block"
        products.map((item) => {
            const { id, productName, productPrice, productImg } = item
            if (cartArray.includes(id)) {
                totalPrice.innerHTML = (Number(totalPrice.innerText) + Number(productPrice)).toFixed(2);

                return eachCartItemContainer.innerHTML +=
                    `<div class="eachCart">` +
                    ` <img src="./img/${productImg}" class="cartImg" alt="">` +
                    `<div class="cartDesc">` +
                    `<h1 class="cartItemName">${productName}</h1>` +
                    `<p class="cartItemPrice">${productPrice}€</p>` +
                    `<i class="fa-solid fa-trash fa-lg" id="remove${id}"></i>` +
                    `<i class="fa-solid fa-plus fa-lg" id="addtocart${id}")></i>` +
                    `<i class="fa-solid fa-minus fa-lg" id="addtocart${id}")></i>` +
                    `</div>` +
                    `</div>`
            }
        })
    } else {
        cartTitle.innerText = 'No Item'
        totalPriceContainer.style.display = "none"
    }
    onRemoveButton();

}

const onRemoveButton = () => {
    const itemInCart = localStorage.getItem("cartItems");
    const itemInCartArray = itemInCart.split(",");

    for (let index = 0; index < itemInCartArray.length; index++) {
        const removedItem = itemInCartArray[index]
        document.getElementById(`remove${removedItem}`).onclick = () => {
            const Itemindex = itemInCartArray.indexOf(removedItem)
            cartItems.splice(Itemindex, 1)
            localStorage.setItem("cartItems", cartItems)
            totalItem.innerText = cartItems.length - 1;
            displayItemInCart();
        }
    }
}

well increment by 1 is ++, and decrement by 1 is --

I think the bigger problem youre going to run into is that unless im mistaken, your cart’s code isnt set up to store a quantity anywhere. It appears to be designed for unique items.

1 Like

Thank you and should I do this or in my code?

++ is an operator. It can go before or after a variable.

let num = 1;
num++; //Num is now 2.
console.log(num); //2
console.log(num++); //will output the current value (2), then will set num to 3.
console.log(num); //3
console.log(++num); //will set num to 4, then output its value, so it will send 4 to the console.
console.log(num); //4

The same applies to --.

Adding a quantity to your code is… far beyond the scope of this thread. You’d be fundamentally modifying pretty much every part of that code.

1 Like

ok thank you for your help and once the variables are indicated I need to modify what in my code for it to work? the + and -?

I indicated your code like this

import { products } from "./items";

// Toggle shopping cart
const shoppingCart = document.getElementById("shoppingCart");
const closeCart = document.getElementById("closeCart");

const itemContainer = document.getElementById('itemContainer');
const cartContainer = document.getElementById("cartContainer");
const eachCartItemContainer = document.getElementById("eachCartItemContainer");
const totalItem = document.getElementById("totalItem");

const cartTitle = document.getElementById("cartTitle")
const totalPrice = document.getElementById("totalPrice");
const totalPriceContainer = document.getElementById("totalPriceContainer");

const storedItems = localStorage.getItem("cartItems")
const cartItems = storedItems !== null
    ? storedItems.split(",")
    : []

let num = 1;
num++; //Num is now 2.
console.log(num); //2
console.log(num++); //will output the current value (2), then will set num to 3.
console.log(num); //3
console.log(++num); //will set num to 4, then output its value, so it will send 4 to the console.
console.log(num); //4

totalItem.innerText = cartItems.length !== null
    ? cartItems.length - 1
    : 0

// Iterate card
for (let index = 0; index < products.length; index++) {
    const { id, productName, productPrice, productImg } = products[index]
    itemContainer.innerHTML +=
        ` <div class="card">` +
        ` <article class="cardImg">` +
        ` <img src="./img/${productImg}" alt="">` +
        `</article> ` +
        ` <div class="itemDescContainer">` +
        `<article class="itemDesc">` +
        `<h1 class="itemName">${productName}</h1>` +
        `<p class="itemPrice">${productPrice}€</p>` +
        ` </article> ` +
        `<div class="addtocart" id="addtocart${id}")'>` +
        `<i class="fa-solid fa-cart-shopping cart"></i>` +
        ` </div>` +
        ` </div>` +
        `</div>`

}

// Add click event listener for card Item
for (let index = 1; index <= products.length; index++) {
    document.getElementById(`addtocart${index}`).onclick = () => {
        if (cartItems.includes(index) === false) {
            totalItem.innerText = cartItems.length;
            cartItems.unshift(index)
            localStorage.setItem("cartItems", cartItems)
        }
    }
}

shoppingCart.onclick = () => {
    cartContainer.classList.add("showCartContainer");
    displayItemInCart();
}

closeCart.onclick = () => {
    cartContainer.classList.remove("showCartContainer");
}

// AddClickEvent for button
const displayItemInCart = () => {
    cartTitle.innerText = `${cartItems.length - 1} Item In cart`;
    eachCartItemContainer.innerHTML = "";
    if (localStorage.getItem("cartItems")) {
        const cartArray = localStorage.getItem("cartItems").split(",");
        totalPrice.innerText = "";
        totalPriceContainer.style.display = "block"
        products.map((item) => {
            const { id, productName, productPrice, productImg } = item
            if (cartArray.includes(id)) {
                totalPrice.innerHTML = (Number(totalPrice.innerText) + Number(productPrice)).toFixed(2);

                return eachCartItemContainer.innerHTML +=
                    `<div class="eachCart">` +
                    ` <img src="./img/${productImg}" class="cartImg" alt="">` +
                    `<div class="cartDesc">` +
                    `<h1 class="cartItemName">${productName}</h1>` +
                    `<p class="cartItemPrice">${productPrice}€</p>` +
                    `<i class="fa-solid fa-trash fa-lg" id="remove${id}"></i>` +
                    `<i class="fa-solid fa-plus fa-lg" id="addtocart${id}")></i>` +
                    `<i class="fa-solid fa-minus fa-lg" id="addtocart${id}")></i>` +
                    `</div>` +
                    `</div>`
            }
        })
    } else {
        cartTitle.innerText = 'No Item'
        totalPriceContainer.style.display = "none"
    }
    onRemoveButton();

}

const onRemoveButton = () => {
    const itemInCart = localStorage.getItem("cartItems");
    const itemInCartArray = itemInCart.split(",");

    for (let index = 0; index < itemInCartArray.length; index++) {
        const removedItem = itemInCartArray[index]
        document.getElementById(`remove${removedItem}`).onclick = () => {
            const Itemindex = itemInCartArray.indexOf(removedItem)
            cartItems.splice(Itemindex, 1)
            localStorage.setItem("cartItems", cartItems)
            totalItem.innerText = cartItems.length - 1;
            displayItemInCart();
        }
    }
}

you would need a function to add to the quantity once you’ve added it, a function to subtract from the quantity when you’ve added it, you’d need to redefine cartItems to hold objects with quantities and id’s, you’d need to change the addtocart function to create a new object in the cartitems container, you’d need to change the displayItem code to handle summing the quantities and display quantities, you’d need to change the remove item code to handle the object filtering…

Basically, you’ll have to rewrite the entire thing. I’m not going to do that for you.

1 Like

ah ok I didn’t know it was a lot of work, sorry.

I wanted to ask you and to display a single cart for example id 7 how to do it?

assuming there is a product with id 7 visible on the screen, document.getElementById('addtocart7').click()

and how is this because I would like to do it in my index.html file via the button?

<button class="explore-btn">
   <a href="#coffee">Explore More</a>
</button>

I’m sorry, you want a button with a text “Explore more” to put something in a shopping cart? Are you trying to drive people away from your website? Because that’s what I would do if a button that suggests one thing (link to page with more information, or popup maybe) does something completely different I didn’t ask for. I’d run away and never come back.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.