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

17,749

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.

Share:
17,749
Mark Rummel
Author by

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, 2022

Comments

  • Mark Rummel
    Mark Rummel almost 2 years

    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!

  • Mark Rummel
    Mark Rummel over 12 years
    Thank 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
    James Allardice about 12 years
    What do you mean by "actually a helper in a library usage"? The code you have posted is perfectly valid.
  • Sithys
    Sithys about 9 years
    ...searched for hours through the web - this works perfectly fine!