I’m trying to make shopping cart front end with localstorage, as there are some modal windows and I need to pass cart items info there. Every time you click add to cart it should create object and it to localstorage. I know I need to put everything in array and push new object to array, after trying multiple solutions – can’t get it to work
That’s what I have (saves only last object):
var itemContainer = $(el).parents('div.item-container');
var itemObject = {
'product-name': itemContainer.find('h2.product-name a').text(),
'product-image': itemContainer.find('div.product-image img').attr('src'),
'product-price': itemContainer.find('span.product-price').text()
};
localStorage.setItem('itemStored', JSON.stringify(itemObject));
You’re overwriting the other objects every time, you need to use an array to hold them all:
http://jsfiddle.net/JLBaA/1/
You may also want to consider using an object instead of an array and use the product name as the key. This will prevent duplicate entries showing up in localStorage.