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));
We can store more user information in a single key this way. In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON.
You can't persist a window object in local storage. You can only store data in the form of strings in local storage, and there is no way to turn the window object into a string so that you can recreate the same window object.
// Get the existing data var existing = localStorage.getItem('myLunch'); // If no existing data, create an array // Otherwise, convert the localStorage string to an array existing = existing ?
Here we are going to learn how to store a JSON object into localStorage. As you know that setItem () method is being used to store data in local storage. Tip: JSON.stringify () can not serialize private members and the datatypes that are not JSON-safe.
I’ll begin by getting persistence through the localStorage window property. To add working “Load” and “Save” buttons that store the tiddlers array as a key-value pair to the localStorage object, and retrieve it from that key-value pair, respectively. 1. Add “Load tiddlers” and “Save tiddlers” buttons
HTML5 localStorage lets you store key/value pairs of data. Both key and value needs to be a string. To store arrays as a key or value you need to encode the array into a JSON string. And while retrieving you need to decode it back to an array.
You're overwriting the other objects every time, you need to use an array to hold them all:
var oldItems = JSON.parse(localStorage.getItem('itemsArray')) || []; var newItem = { '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() }; oldItems.push(newItem); localStorage.setItem('itemsArray', JSON.stringify(oldItems));
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With