user10543225
user10543225

Reputation:

How do I get local storage to save different shopping cart items?

I'm building an eCommerce website and I'm using local-storage for saving data to the shopping cart. However, I'm having some issues with it:

  1. I can't add different items without losing the old ones (I guess the rows don't save); I noticed as soon as I click add to cart it overwrites the row with the new data. (I'm thinking it's probably that for loop that overwrites the data from i=1 again) as shown this is what I see https://i.sstatic.net/E4QNf.jpg

  2. the remove button doesn't seem to be working properly as well; it's driving me nuts!

My code might be all over the place so my apologies and any help are really appreciated.

selected-product.html

<div onclick="additem()" id="add-item-to-cart">
  <h4>ADD TO CART</h4>
</div>

shopping-bag.html

<table>
  <tr>
    <th>IMAGE</th>
    <th>ITEM</th>
    <th>COLOR</th>
    <th>PRICE</th>
    <th>QUANTITY</th>
  </tr>

  <tr class="item-row"></tr>

  <td id="cart-total-price-title">TOTAL:</td>
  <td id="cart-total-price">$0.00</td>
</table>

cart.js

var itemCounter = 0;
var loopNum = 1;
function additem() {

  itemCounter++;
  loopNum++;
  localStorage.setItem('item-count', itemCounter);
  localStorage.setItem('item-loop', loopNum);
  // alert(itemCounter);
  addToCart();
}

function updateCartTotal() {
  //
  // Get the first table in the document.
  var counter = localStorage.getItem('item-count');
  var loop = localStorage.getItem('item-loop');
  //alert('counter'+counter);
  var table = document.getElementsByTagName('table')[0];
  var count = 0;
  var itemPrice = localStorage.getItem('saved-Price');
  var totalPriceElement = document.getElementById('cart-total-price');
  var cartRows = document.getElementsByClassName('item-row');
  var cellOfItemColor = localStorage.getItem('saved-colorArray').split(',');
  var cellOfitemQuantityInput = localStorage.getItem('saved-quantityArray').split(',');
  var cellOfItemName = localStorage.getItem('saved-itemArray').split(',');
  var imageArray = localStorage.getItem('saved-imageArray').split(',');



  console.log(cellOfItemColor[0] + cellOfitemQuantityInput);
  for (var i = 1; i <= counter; i++) {

    var row = table.insertRow(i);
    var cellOfItemImage = row.insertCell(0);
    row.insertCell(1).innerText = cellOfItemName[i - 1];


    row.insertCell(2).innerText = cellOfItemColor[i - 1];

    row.insertCell(3).innerText = itemPrice;

    row.insertCell(4).innerText = cellOfitemQuantityInput[i - 1];

    var cellOfItemRemove = row.insertCell(5);

    var image = document.createElement('img');
    image.src = imageArray[i - 1];
    image.setAttribute("width", "100");
    image.setAttribute("height", "100");
    cellOfItemImage.appendChild(image);

    var removeRow = document.createElement("BUTTON");
    removeRow.style.color = "black";
    removeRow.style.padding = '10px';
    removeRow.style.fontFamily = "Roboto, sans-serif, verdana, tahoma";
    removeRow.style.letterSpacing = '3px';
    removeRow.style.fontWeight = 'bold';
    removeRow.innerText = "REMOVE";
    cellOfItemRemove.append(removeRow);

    localStorage.setItem('item-row', row);
    removeRow.addEventListener('click', function () {
      table.deleteRow(1);
      localStorage.deleteItem('item-row');

    });


    var totalPrice = 0;
    for (var i = 0; i < cartRows.length; i++) {

      totalPrice = totalPrice + (itemPrice * 1 /*inputQuantityValue.value*/);
      count++;
    }

    totalPrice = '$' + totalPrice.toFixed(2);
    totalPriceElement.innerHTML = totalPrice;
    console.log(count + ' Total: ' + totalPrice);

  }

  var colorArray = [];
  var quantityArray = [];
  var itemnameArray = [];
  var itemimageArray = [];
  function addToCart() {


    var productQuantity = document.getElementById("qty").value;
    var productColor = document.getElementById("clr-list").value;
    var productModel = document.getElementById("model").value;
    var currTitle = document.getElementById('product-title').innerHTML;
    var productImageLocation = document.getElementById("product-img").src;


    colorArray.push(productColor);
    localStorage.setItem('saved-colorArray', colorArray);

    quantityArray.push(productQuantity);
    localStorage.setItem('saved-quantityArray', quantityArray);

    itemnameArray.push(currTitle);
    localStorage.setItem('saved-itemArray', itemnameArray);

    itemimageArray.push(productImageLocation);
    localStorage.setItem('saved-imageArray', itemimageArray);



    if (productQuantity < 1) {
      alert('Product quantity has to be at least one');
    }
    else {
      alert('Item added! ' + currTitle + " Quantity: " + productQuantity + " Color: " + colorArray + " Model: " + productModel + 'img src : ' + productImageLocation);
      updateCartTotal();
    }
  }
}

Upvotes: 1

Views: 921

Answers (1)

G&#225;bor H&#233;ja
G&#225;bor H&#233;ja

Reputation: 495

You are not reading the arrays as arrays from the local storage but rather than expecting a string of them separated by colons - even if it would work on some browsers, having any item containing "," in a property would break this.

You can store arrays as JSON, and in fact JSON supports more than this, you could consider storing an array with the items storing all their properties.

Also, you should really not trust the browser with the cart, especially handling prices and doing payments, as all the data can be easily manupulated.

Upvotes: 1

Related Questions