Reputation: 1659
I am developing a shopping cart. The products in the cart are populated by this local storage array
{id: "1280-01-601-0179-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514502694923", name: "NRP CABLE ASSEMBLY", price: "$32", quantity: "33"}
{id: "1660-01-519-2834-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514573672302", name: "SEPARATOR WATER,AIRCRAFT AIR CON", price: "$322", quantity: "1"}
{id: "1510-01-312-3501-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514542566148", name: "AIRPLANE UTILITY", price: "$90", quantity: "1"}
this is js code
var arrayLength = cartarry.length;
for (var i = 0; i < arrayLength; i++) {
var id = cartarry[i].id;
var name = cartarry[i].name;
var price = parseInt(cartarry[i].price.replace('$',""))
var quantity = parseInt(cartarry[i].quantity);
var linetotal = price * quantity;
var itemcontainer = document.getElementById('myContent');
// itemcontainer.innerHTML = '';
//Do something
var itemcard = `
<div class="product" id="${id}">
<div class="product-details">
<div class="product-title">Dingo Dog Bones</div>
<p class="product-description"> ${name}</p>
</div>
<div class="product-price" id='productprice'>${price}</div>
<div class="product-quantity">
<input type="number" id='productquantity' value=${quantity} min="1">
</div>
<div class="product-removal">
<button class="remove-product">
Remove
</button>
</div>
<div class="product-line-price" id='productlineprice' >${linetotal}</div>
</div>
`
;
itemcontainer.innerHTML += itemcard;
calculatelinetotal()
}
I want to recalculate the cart total price on quantity change. So updating the local storage array on quantity change and then recalculating to get the updated price and final cost. I was able to get the id of the changing quantity parent with this
$('.product-quantity input').change( function() {
var id = $(this).parents('.product')[0].id;
});
so an example of
console.log(id) // 1280-01-601-0179-OkqcPp3xJwfgmNinwGsKZmAa8xt1-1514502694923"
how can I update the quantity of the local storage array for a specific id and delete the array for a specific id?
Upvotes: 1
Views: 2386
Reputation: 16495
In local storage you can only store strings. So the simplest thing to do is to use JSON.stringify
and JSON.parse
to store objects/arrays json encoded. Just rewrite the item completely.
Basically:
function updateArray (key, index, value) {
var array = JSON.parse(localStorage.getItem(key));
array[idx] = value;
localStorage.setItem(key, JSON.stringify(array));
}
Upvotes: 1