Shopping Cart Array

Hi, I created a shopping cart using localStorage, I can call the arrays up on my cart page but I can’t see to get the prices of each item in the cart.

function productItem(img, name, price, id) {
    this.img = img;
    this.name = name;
    this.price = price;
    this.id = id;
}


let myCartItem = localStorage.getItem("myCartItem");
myCartItem = JSON.parse(myCartItem);

if (myCartItem === null) {
    console.log('Cart is Empty');
} else {
    myCartItem.forEach(e => {
        console.log(e);
    })
}

var html = "<table border='1|1'>";
for (var i = 0; i < myCartItem.length; i++) {
    html += "<th>" + "Image" + "</th>";
    html += "<th>" + "Product Name" + "</th>";
    html += "<th>" + "Price" + "</th>";
    html += "<tr>";
    html += "<td>" + '<img src="' + myCartItem[i].img + '">' + "</td>";
    html += "<td>" + myCartItem[i].name + "</td>";
    html += "<td>" + "R" + myCartItem[i].price + "</td>";

    html += "</tr>";

}
html += "</table>";
document.getElementById("cartSection").innerHTML = html;

The above is on my cart script and the code below is found on my product script;

function productItem(img, name, price, id) {
  this.img = img;
  this.name = name;
  this.price = price;
  this.id = id;
}

let item1 = new productItem(
  "Images/HomePG-Thumb/trek-marlin-5-2020-sample.jpg",
  "Trek Marlin 5 - 2020",
  7499.99,
  "marlin520"
);

let myProductItem = [item1, item2, item3, item4, item5, item6, item7, item8];
let myCartItem = [];

function saveToCart(myItem) {
  myCartItem.push(myItem);
  localStorage.setItem("myCartItem", JSON.stringify(myCartItem));
  let total = Number(localStorage.getItem("total"));
  if (total === null) {
    localStorage.setItem("total", myItem.price);
  } else {
    total += Number(myItem.price);
    localStorage.setItem("total", myItem.price);
  }
  alert('You added ' + myItem.name + ' to your cart.')
  /*console.log(myItem.name);
  console.log(myItem.price);
  console.log(myItem.img);*/
}

let count = 0;
myProductItem.forEach(item => {
  count++;
  document.getElementById(item.id).innerHTML +=
    '<img src="' +
    item.img +
    '" alt="Trek Marlin 5">' +
    "<br>" +
    item.name +
    "<br>" +
    "R" +
    item.price;

  let buyButton = document.getElementById("cart" + count);
  buyButton.onclick = e => {
    saveToCart(item);
  };
});

I just added the one item to the question, but there are 8 of them in my script.

How will I the go by to get the prices only?

On my HTML page I added the below to my ‘Buy Now’ button:

<button type="button" class="btn btn-link addtocart" id="cart1" onclick="myFunction()" 
href="#" data-name="Trek Marlin 5 - 2020" data-price="7499.99">Buy Now</button>

Thanks in Advance :slight_smile:

Hello and welcome :slight_smile:!

I don’t really see something wrong with your code. Where are You expecting to see the prices but are not shown now? Did You check the console for any errors?

One problem I can see is that Your Buy Now button should reference the id of the product somewhere, like <button data-id="product_1" type="button" class="btn btn-link addtocart">Buy Now</button>, then in Your script, You should listen for any addtocart button click.

Look at this sample (used jQuery and Bootstrap–here’s a working sample: https://jsfiddle.net/skaparate/b2kyvd7L/28/):

<!-- this is just the container where the products are shown -->
<div class="products card-columns"></div>
function product(id, name, img, price) {
	this.id = id;
  this.name = name;
  this.img = img;
  this.price = price;
}

const products = [
  new product('pid1', 'Product 1', 'https://www.webdesignerdepot.com/cdn-origin/uploads/2008/11/sample-graphic.gif', 100),
  new product('pid2', 'Product 2', 'https://www.webdesignerdepot.com/cdn-origin/uploads/2008/11/sample-graphic.gif', 100),
  new product('pid3', 'Product 3', 'https://www.webdesignerdepot.com/cdn-origin/uploads/2008/11/sample-graphic.gif', 100)
];

const container = $('.products');

products.forEach((i) => {
	container.append(`
  <div class="card">
  	<img src="${i.img}" class="card-img-top" />
    <div class="card-body">
    	<div class="card-title">${i.name}</div>
    	<p class="card-text">$${i.price}</p>
      <footer><button class="btn btn-primary addtocart" data-id="${i.id}">Buy Now</button></footer>
    </div>
  </div>
  `);
});

function saveToCart(event) {
	event.preventDefault();
	const target = event.target;
  const productId = target.dataset.id;
  const product = products.find((i) => i.id === productId);
  console.debug(product);
  
  if (product) {
  	// Save it to the localStorage cart
  } else {
  	// The product wasn't found... maybe someone tampered with the HTML?
  }
}

$('.addtocart').on('click', saveToCart);

Hi, thanks for the welcome :slight_smile:

Currently on VSCode when I add the item to my cart, it goes to localStorage, then I iterate over the items in the array that the user selected and set them in a table on my cart page. However, if I navigate to the cart page before any item is added I get this error “Uncaught TypeError: Cannot read property ‘forEach’ of null”

Also, I need to sum up the items in my cart someway to get a count and total items in my cart, but accessing the values and getting the count I am uncertain about.

Should I remove the onclick function from the button and rather add the id to the button of each product?

That should be expected, since it’s supposed to be empty :slight_smile:. However, You should try to fix every error You find.

You should have two stored items: one for all the products and another for the current cart. When you display the current cart, You read the cart from the localStorage and iterate over the items (sum the prices in the loop). The actual product list should not be linked, in any way, to the cart, since the first should no be modified by the end user.

Yes, that’s one way to do it. The important thing is that any .addtocart button has some way to identify the product.

By the way, this project is only for testing or learning, right? I assumed so, but if not (if it’s a real application for a real online shop), what You’re doing is risky, because the product information could be modified by the user (using the web developer tools, for example).

Only for learning :slight_smile:

So on the cart page I should save this to localStorage as well? How will I however get the price of the items in the cart?

Cool then :slight_smile:!

No.

You should have a list of products predefined and saved to the localStorage (let’s call it product_list, for example). Then You iterate the products on the website to display them and add an Add To Cart button.

Now, whenever a user clicks the Add To Cart button, you load the product_list, find the product that matches the one on the list, and that one is added to a different localStorage item (call it cart).

When the user goes to see the cart, that’s when You load the cart items and iterate over them, where You can sum up the prices. The cart should be updated every time a new item is added or removed.

Hope it helps :slight_smile: