Reputation: 45
i was working on a online shop . now everything is good but i want to do something to delete a product from my cart .here is its code can you help me?
function displaycart() {
let cartitems = localStorage.getItem("productsincart");
cartitems = JSON.parse(cartitems);
let productcontainer = document.querySelector(".products-container");
let cartcost = localStorage.getItem("totalcost");
if (cartitems && productcontainer ) {
Object.values(cartitems).map(item => {
productcontainer.innerHTML += '<tr><td><button class="bd">close</buttton></td><td>'+ item.nam + '</td><td>' + item.price * item.incart + '</td><td>' + item.incart + '<td>افزودن</td></tr>'
});
let productmab = document.querySelector(".mabb");
productmab.innerHTML += cartcost;
}
}
let bv = document.querySelector(".bv");
let bd = document.querySelectorAll(".bd")
let cc = localStorage.getItem("productsincart")
let cartiteme = JSON.parse(localStorage.getItem("productsincart"))
bv.addEventListener("click" , () => {
localStorage.clear()
window.alert("refresh the page")
})
displaycart()
and here is the localstorge ...
how can i delete one of them in productsincart ?
Upvotes: 0
Views: 87
Reputation: 31
That could be an useful function in your case:
function removeItem(index) {
let cartitems = JSON.parse(localStorage.getItem("productsincart"));
cartitems.splice(index, 1);
localStorage.setItem('productsincart', JSON.stringify(cartitems));
}
Upvotes: 1
Reputation: 414
One way is to give them ids. You could use npm i --save uuid
to get random ids.
Your local storage should look like this:
[{"id": "342324", "product": "item"}, /* then repeated for every item */]
Then you remove the entry by creating a new array that doesn't contain the object with the specified id, then you replace the previous local storage array with the new one. You can filter like this:
const newLocalStorage = JSON.parse(localStorage.getItem("productsincart").filter((product) => product.id !== id);
.
Then set local storage to newLocalStorage
.
Upvotes: 0
Reputation: 5176
cartitems is an array and the entire array is stored in local storage. You just need to remove the desired item from the array and then write it back to local storage, which will overwrite the previous value.
Upvotes: 0