HTML5/JavaScript: Store Dynamic Variable Name and Value in localStorage
Solution 1
Try this:
localStorage['movie'+movieID] = 'yes';
Solution 2
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);
Solution 3
I think
localStorage.setItem('movie' + movieID, 'yes');
is actually a helper in a library usage and is not official.
Solution 4
Check out square brackets for properties.
Mark Rummel
I'm a modern web designer. I have enjoyed designing and building websites for my clients for over 10 years. I have extensive experience in many web technologies, including HTML5, CSS3, javascript, jQuery, LESS, PHP, MySQL, Wordpress, MailChimp, PayPal, Stripe, and more.
Updated on June 29, 2022Comments
-
Mark Rummel almost 2 years
I would like to store the value
yes
into localStorage with a key ofmovie1
using javascript. However, I want the1
part of the key to be dynamic based on whatevermovieID
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!
-
Mark Rummel over 12 yearsThank you for the jsfiddle. This works and is basically the same answer as stewe, but a little more in depth...I just prefer being able to see the answer right away on stackoverflow without having to switch over to jsfiddle.
-
James Allardice about 12 yearsWhat do you mean by "actually a helper in a library usage"? The code you have posted is perfectly valid.
-
Sithys about 9 years...searched for hours through the web - this works perfectly fine!