I have three different product arrays, here's one:
let necklaces = [
{
id: "BlueHeartNecklace",
cat: "necklaces",
price: "$25",
name: "Blue Heart Necklace",
img: "images/custom_jewlery/necklaces/61-t5HCxAEL._AC_UL480_QL65_.jpg",
orders: 0,
},
{
id: "BlueTileNecklace",
cat: "necklaces",
price: "$14",
name: "Blue Tile Necklace",
img: "images/custom_jewlery/necklaces/71pYceJZEgL._AC_UL480_QL65_.jpg",
orders: 0,
},
{
id: "GreenPearNecklace",
cat: "necklaces",
price: "$32",
name: "Green Pear Necklace",
img: "images/custom_jewlery/necklaces/61BHPeEKb7L._AC_UL480_QL65_.jpg",
orders: 0,
},
];
Every time I add one of the products to the cart, it shows me the last product in the array. here's the code to display the array:
let necklace;
function showNecklaces() {
display.innerHTML = "";
for (let index = 0; index < necklaces.length; index++) {
necklace = necklaces[index];
display.innerHTML += `<div ${necklaces[index].name}>
${necklaces[index].name} , ${necklaces[index].price} ,
<img src="${necklaces[index].img}"></div>
<button class="btn btn-primary" onclick='add(necklace)'> Add to cart</button>
`;
}
}
Here's the function where I add products to the cart:
let cart = [];
function add(product) {
console.log(product);
cart.push(product);
}
And here's the function where I click when I want to have the whole cart displayed:
function showCart() {
display.innerHTML = "";
for (let index = 0; index < cart.length; index++) {
display.innerHTML += `<div ${cart[index].name}>
<button class="btn btn-danger" onClick='remove(${index})'>Remove</button>;
${cart[index].name} , ${cart[index].price} ,
<img src="${cart[index].img}"></div>`;
}
}