I have three html pages with different products. I am using local storage and looping over the products using the button index. It was all good until I realized that when I click the button from another page it takes index one again and displays the first item from the object again. Please tell me a way to integrate all my pages together so the desired items are displayed in the cart. Here is some JS code that I am using.
for(let i=0; i< carts.length; i++) {
carts[i].addEventListener('click', () => {
cartNumbers(products[i]);
totalCost(products[i]);
}); }
function displayCart() {
let cartItems = localStorage.getItem('productsInCart');
cartItems = JSON.parse(cartItems);
let cart = localStorage.getItem("totalCost");
cart = parseInt(cart);
let productContainer = document.querySelector('.products');
if( cartItems && productContainer ) {
productContainer.innerHTML = '';
Object.values(cartItems).map( (item, index) => {
productContainer.innerHTML +=
`<div class="product"><ion-icon name="close-circle" color="primary"></ion-icon><img src="Images/${item.tag}.jpg" />
<span class="sm-hide">${item.name}</span>
</div>
<div class="price sm-hide">${item.price}</div>
<div class="quantity">
<ion-icon class="decrease" name="arrow-dropleft-circle" color="primary"></ion-icon>
<span>${item.inCart}</span>
<ion-icon class="increase" name="arrow-dropright-circle" color="primary"></ion-icon>
</div>
<div class="total">${item.inCart * item.price}</div>`;
});
productContainer.innerHTML += `
<div class="basketTotalContainer">
<h4 class="basketTotalTitle">Basket Total</h4>
<h4 class="basketTotal">${cart}</h4>
</div>`
Here is my object:
let carts = document.querySelectorAll('.cart');
let products = [
{
name: "EMPOWERED WOMEN",
tag: "1",
price: 29.95,
inCart: 0
},
{
name: "WOMEN IN STEM",
tag: "2",
price: 30.95,
inCart: 0
},
{
name: "ROSIE THE RIVETER",
tag: "3",
price: 40.95,
inCart: 0
},
{
name: "FEMINIST FLOWERS",
tag: "4",
price: 29.95,
inCart: 0
}, ];
Here is html for products1 page. Products2 html also has same css but diferent products.
<div class="container" align="center"><br>
<h1>FEMME T-SHIRTS</h1>
<br><br>
<table class="table" style="width:100%">
<thead>
<tr>
<td align="center">
<img src="Images/1.jpg" class="thumbnail">
<p>EMPOWERED WOMEN EMPOWER WOMEN</p>
<p>$ 29.95 USD</p>
<p><a class="btn cart px-auto">ADD TO CART</a>
</p>
</td>
<td align="center" id="2">
<img src="Images/2.jpg" class="thumbnail">
<p>WOMEN IN STEM</p>
<p>$ 29.95 USD</p>
<p><a class="btn cart px-auto">ADD TO CART</a>
</p>
</td>
<td align="center">
<img src="Images/3.jpg" class="thumbnail">
<p>ROSIE THE RIVETER</p>
<p>$ 29.95 USD</p>
<p><a class="btn cart px-auto" id="3">ADD TO CART</a>
</p>