Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML5/JavaScript: Store Dynamic Variable Name and Value in localStorage

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!

like image 743
Mark Rummel Avatar asked Mar 27 '12 19:03

Mark Rummel


People also ask

Can we store JavaScript objects directly into localStorage?

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.

How can I store multiple values inside one localStorage key?

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.


4 Answers

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);
like image 64
Annie Avatar answered Oct 02 '22 00:10

Annie


I think

localStorage.setItem('movie' + movieID, 'yes');

is actually a helper in a library usage and is not official.

like image 44
user1450955 Avatar answered Oct 01 '22 22:10

user1450955


Try this:

localStorage['movie'+movieID] = 'yes';
like image 39
stewe Avatar answered Oct 01 '22 22:10

stewe


http://jsfiddle.net/ZwhBY/

Check out square brackets for properties.

http://www.jibbering.com/faq/faq_notes/square_brackets.html

like image 42
Rick Avatar answered Oct 02 '22 00:10

Rick