surgiie surgiie - 3 months ago 12
jQuery Question

How to use a string value containing Web Storage type to call Web Storage API functions in JS/JQuery?

Im writing a small script in js/jquery that saves form fields for users to save forms and finish them later, currently i was using sessionStorage to accomplish this no problem, but id like to enhance the script to allow dev's to define if they want to use either local or sessionStorage, but im not sure how to go about it as im still a noob in this field:P. In my head i have this plan where devs can define an attribute, lets say 'data-storage-type' on the form tag and they can value it with either session or localStorage and then i can use Jquery to get the value as such:

value = $(this).attr('data-storage-type');


then go from there to do my storage saving, but im still new to jquery/js so im wondering if i can call the storage type they defined in this variable to call the get and setItem functions that are part of the built in Webstorage api.

so if value = "localStorage", could i call it somehow as such:

value.getItem(arg);


Cause im pretty sure you cant do this:

"localStorage".getItem(arg);


Is there a way i can call this? Or is there a better way to tackle this? Thanks!

Answer

you can do something like that

window[value].getItem(arg);// where value can be 'localStorage' string

or you can use switch statement

switch(value) {
  case 'localStorage':
    localStorage.getItem(arg); 
    break;
  case 'sessionStorage':
    sessionStorage.getItem(arg); 
    break;
}
Comments