I would like to store the value yes
into localStorage with a key of movie1
using javascript. However, I want the 1
part of the key to be dynamic based on whatever movieID
is set to.
This is what I currently have, but it isn't working:
movieID = 1;
localStorage.movie + movieID = 'yes';
Any thoughts or insight on how I can accomplish this would be greatly appreciated. Thanks!
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. parse method.
A single key can only have a single string value in localStorage. You can have multiple keys with different names, or you can do some encoding of the values. For example, you could put all your values in an Array, then encode it using JSON. stringify() and store the result in localStorage.
You can use the setItem function to store values in local storage:
localStorage.setItem('movie' + movieID, 'yes');
Then later when you want to check the value, you can use
localStorage.getItem('movie' + movieID);
I think
localStorage.setItem('movie' + movieID, 'yes');
is actually a helper in a library usage and is not official.
Try this:
localStorage['movie'+movieID] = 'yes';
http://jsfiddle.net/ZwhBY/
Check out square brackets for properties.
http://www.jibbering.com/faq/faq_notes/square_brackets.html
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