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