Changing quantity as the displayed number

34 views Asked by At

I have a problem with changing quantity as the displayed number. When I add products to the cart, everything works fine. For example, adds 5 products to the cart. However, when I click the trash icon to remove the product, the quantity instead of decreasing by one decreases to zero.

Thank you in advance!

let cartQuantityNr = 0;
let cartQuantitySpan = document.querySelector(".cart-quantity");
let cartQuantitySpanHome = document.querySelector(".cartQuantity");

// Removing item from cart
const removeCartItem = () => {
  let removeCartItemBtn = document.querySelectorAll(".cart .rm-item");
  removeCartItemBtn.forEach(e => {
    e.addEventListener("click", () => {
      e.parentElement.parentElement.remove();
      cartQuantityNr--;
      console.log(cartQuantityNr);
      cartQuantitySpan.innerHTML = "(" + cartQuantityNr + ")";
      cartQuantitySpanHome.innerHTML = cartQuantityNr;
    })
  })
}

// Quantity spans 
const quantitySpans = () => {
  cartQuantityNr++;
  cartQuantitySpan.innerHTML = "(" + cartQuantityNr + ")";
  cartQuantitySpanHome.innerHTML = cartQuantityNr;
}

Quantity span 1 Quantity span 2 Console

1

There are 1 answers

0
Milos On

It looks like the source of your data is in HTML.

I would suggest that you keep your data in JavaScript and only reflect information from JavaScript onto HTML.

For example, your cart should look something like this:

const cart = [
  {
    id: 1,
    title: 'Some product',
    quantitty: 2
  },
  {
    id: 2,
    title: 'Second product in cart',
    quantity: 5
  }
]

and that's where you update quantity +1 or -1, or remove item when it's quantity is 0. And whenever something changes, calculate new total quantity of items and "write" it to HTML element.