I'm currently working on a shopping cart that pulls products from a json-server. So far, I've successfully displayed the products, added the functionality to add items to the cart, and show the quantity. However, I'm facing a roadblock with the increment and decrement functions. The goal is for the product.count property to change whenever the user clicks on the + and - buttons (which is used to display in the cart table). Below is my code:
load cart from localstorage
function loadCart() {
let products = JSON.parse(localStorage.getItem('products'));
let cartTotalItem = document.querySelector('.cart__value');
cartTotalItem.textContent = products.length;
products.forEach(product => {
let cartItem = document.createElement('tr');
cartItem.innerHTML = `<td><img src="${product.imgSrc}" alt='product image'></td>
<td>${product.name}</td>
<td><span class='cart-price'>${product.price},000vnd</span></td>
<td>
<button action="remove" onclick='decrease()'>-</button>
<input name='product' class="product__quantity" type="number" min='1' max='100' value='${product.count}'>
<button action="add" onclick='change()' >+</button>
</td>
<td><span class='cart-total-value'>${parseInt(product.price) * product.count},000vnd</span></td>
<td>
<button class="delete--item"><i class="far fa-trash-alt"></i></button>
</td>`;
tableBody.appendChild(cartItem);
});
}
My approach to implementing the function:
function change() {
let products = JSON.parse(localStorage.getItem('products'));
for (let i = 0; i < products.length; i++) {
let inputValue = document.querySelector('.product__quantity').textContent
inputValue = products[i].count++
localStorage.setItem('products', JSON.stringify(products))
}
}
function decrease() {
let products = JSON.parse(localStorage.getItem('products'));
for (let i = 0; i < products.length; i++) {
let inputValue = document.querySelector('.product__quantity').value
inputValue = products[i].count--
localStorage.setItem('products', JSON.stringify(products))
}
}
The issue I'm facing is that I have to refresh the page for the changes to be reflected. Any help would be greatly appreciated.