Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Shopping cart problem -localstorage

D3x73r

New Coder
Hello guys, I cant find problem why my javascript isnt working. Problem is I think with localstorage, when I reload webpage content in cart-box should stay there but it only save first content-box that I added to cart, others disappear but their value like $ stay in total amount . And other issue is that when I try to add same item twice it should give a message " alert('you have already added this item to cart'); " its not working, but when I reload page then that popup shows up as many times as there was content-box that didnt show.

JavaScript:
function ready(){
  //remove item from cart
  var removeCartButtons = document.getElementsByClassName('cart-remove');
  for(var i = 0; i < removeCartButtons.length; i++) {
    var button = removeCartButtons[i];
    button.addEventListener('click', removeCartItem);
  }
  // Quantity Change
  var quantityInputs = document.getElementsByClassName('cart-quantity');
  for(var i = 0; i < quantityInputs.length; i++) {
    var input = quantityInputs[i];
    input.addEventListener('change', quantityChanged);
  }
  //add to cart
    var addCart = document.getElementsByClassName('add-cart');
    for(var i = 0; i < addCart.length; i++) {
      var button = addCart[i];
      button.addEventListener('click', addCartClicked);
    }
    loadCartItems();
  }


//remove Cart Item
function removeCartItem(event){
  var buttonClicked = event.target;
  buttonClicked.parentElement.remove();
  updatetotal();
  saveCartItems();
}
//Quantity Change
function quantityChanged(event){
  var input = event.target;
  if (isNaN(input.value) || input.value <= 0) {
    input.value = 1;
  }
  updatetotal();
  saveCartItems();
}



//Add Cart Funcion
function addCartClicked(event){
  var button = event.target;
  var shopProducts = button.parentElement;
  var title = shopProducts.getElementsByClassName('product-title')[0].innerText;
  var price = shopProducts.getElementsByClassName('price')[0].innerText;
  var productImg = shopProducts.getElementsByClassName('product-img')[0].src;
  addProductToCart(title, price, productImg);
  updatetotal();
  saveCartItems();
}
function addProductToCart(title, price, productImg){
  var cartShopBox = document.createElement('div');
  cartShopBox.classList.add('cart-box');
  var cartItems = document.getElementsByClassName('cart-content')[0];
  var cartItemsNames = cartItems.getElementsByClassName('cart-product-title');
  for (var i = 0; i < cartItemsNames.length; i++){
    if (cartItemsNames[i].innerText == title){
      alert('you have already added this item to cart');
      return;
    }
  }
  var cartBoxContent = `
  <img src="${productImg}" alt="" class="cart-img"/>
  <div class="detail-box">
    <div class="cart-product-title">${title}</div>
    <div class="cart-price">${price}</div>
    <input type="number" name="" id="" value="1" class="cart-quantity"/>
  </div>

  <i class="bx bx-trash-alt cart-remove" ></i>`;
  cartShopBox.innerHTML = cartBoxContent;
  cartItems.append(cartShopBox);
  cartShopBox
  .getElementsByClassName('cart-remove')[0]
  .addEventListener('click', removeCartItem);
  cartShopBox
  .getElementsByClassName('cart-quantity')[0]
  .addEventListener('change', quantityChanged);
  saveCartItems();
}




//Update total
function updatetotal() {
  var cartContent = document.getElementsByClassName('cart-content')[0];
  var cartBoxes = cartContent.getElementsByClassName('cart-box'); // Promenio sam ovaj red
  var total = 0;

  for (var i = 0; i < cartBoxes.length; i++) {
    var cartBox = cartBoxes[i];
    var priceElement = cartBox.getElementsByClassName('cart-price')[0];
    var quantityElement = cartBox.getElementsByClassName('cart-quantity')[0];
    var price = parseFloat(priceElement.innerText.replace('$', ''));
    var quantity = quantityElement.value;
    total += price * quantity;
  }
// If number is not whole
total = Math.round(total * 100) / 100;
  document.getElementsByClassName('total-price')[0].innerText = "$" + total;
  //save total to localStorage
  localStorage.setItem('cartTotal', total);
}



//Keep item in cart on refresh

function saveCartItems(){
  var cartContent = document.getElementsByClassName('cart-content')[0];
  var cartBoxes = cartContent.getElementsByClassName('cart-box');
  var cartItems = [];

  for (var i = 0; i< cartBoxes.length; i++){
    cartBox = cartBoxes[i];
    var titleElement = cartBox.getElementsByClassName('cart-product-title')[0];
    var priceElement = cart.getElementsByClassName('cart-price')[0];
    var quantityElement = cartBox.getElementsByClassName('cart-quantity')[0];
    var productImg = cartBox.getElementsByClassName('cart-img')[0].src;

    var item = {
      title: titleElement.innerText,
      price: priceElement.innerText,
      quantity: quantityElement.value,
      productImg: productImg,
    };
    cartItems.push(item);
  }
  localStorage.setItem('cartItems', JSON.stringify(cartItems));
}


//loads in cart
function loadCartItems() {
  var cartItems = localStorage.getItem('cartItems');
  if (cartItems){
    cartItems = JSON.parse(cartItems);

    for (var i = 0; i < cartItems.length; i++){
      var item = cartItems[i];
      addProductToCart(item.title, item.price, item.productImg);

      var cartBoxes = document.getElementsByClassName('cart-box');
      var cartBox = cartBoxes[cartBoxes.length - 1];
      var quantityElement = cartBox.getElementsByClassName('cart-quantity')[0];
      quantityElement.value = item.quantity;
    }
  }

  var cartTotal = localStorage.getItem('cartTotal');
  if(cartTotal) {
    document.getElementsByClassName('total-price')[0].innerText = "$" + cartTotal;
  }
}
 
That add product to cart function seems to be loading only first with [0] and maybe it should load all and iterate through them. That [0] in add product to cart function seems like one of your problems, unsure about other. Also, when did you make an element with class 'cart-content' or was that in HTML? Also you are adding event listeners before loading content so no event listeners are added upon reload with ready(). You are calling ready as it seems you must be, correct? You do realize that you are updating localStorage with ready() and adding each item to cart, correct? In updating cartItems in both functions you are using var not let so it is same variable in load content and save content and cartItems becomes with a length of 1 so only first should be loading. Otherwise it seems like it should work. Problems solved? X E.
 
Last edited:

New Threads

Latest posts

Buy us a coffee!

Back
Top Bottom