'Delete a product on cart and localStorage
I'm currently on student project where I'm stuck on delete product on cart page I have no problem to delete them on the front page but when it come to remove it too on localStorage honestly I don't know what to do.
I know that using localStorage.setItem allow to update it when necessary but on the code that I wrote I don't know where to put correctly.
I wrote this :
// Targeting arrays
let deleteButton = document.querySelectorAll('.deleteItem');
let localStorageProducts = localStorage.getItem('Produits');
for (let i = 0; i < deleteButton.length; i++) {
// Get all remove buttons
let buttons = deleteButton[i];
// Link to his parent
let myData = deleteButton[i].closest('article');
let getStorageProducts = JSON.parse(localStorageProducts);
buttons.addEventListener("click",() =>
{
getStorageProducts.forEach(localStorageProducts =>{
if(localStorageProducts.id === myData.dataset.id){
// Delete the product
myData.remove();
localStorage.setItem('Produits',(JSON.stringify([localStorageProducts])));
}
})
})
}
<section id="cart__items">
<article class="cart__item" data-id="{product-ID}" data-color="{product-color}">
<div class="cart__item__img">
<img src="../images/product01.jpg" alt="Photographie d'un canapé">
</div>
<div class="cart__item__content">
<div class="cart__item__content__description">
<h2>Nom du produit</h2>
<p>Vert</p>
<p>42,00 €</p>
</div>
<div class="cart__item__content__settings">
<div class="cart__item__content__settings__quantity">
<p>Qté : </p>
<input type="number" class="itemQuantity" name="itemQuantity" min="1" max="100" value="42">
</div>
<div class="cart__item__content__settings__delete">
<p class="deleteItem">Supprimer</p>
</div>
</div>
</div>
</article>
</section>
An example , here I have 4 products : Products in Localstorage
When I click on one of the remove button it's gonna delete 3 of them and one left :
How could I delete them one by one ?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
