Getting the value of a variable from localStorage from a different javascript file

47,240

This shouldn't be working at all. Its localStorage (JS is very case sensitive), and to save an item, you use setItem, change your syntax to:

//You would not define var _NSCaseId and save the var, you save a string key
localStorage.setItem('_NSCaseId', nsId); //set

And to get

localStorage.getItem('_NSCaseId');

See DOM Storage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage

Share:
47,240
MrJR
Author by

MrJR

Updated on July 23, 2022

Comments

  • MrJR
    MrJR almost 2 years

    having a problem using localstorage in javascript. I have two javascript files and one multi-page html file. I'm setting the value of a variable to store in local storage in the home.js class and I then want to get the value of the same variable in my editCase.js class. Is this possible? The goal here is to use the variable several places in the html file.

    home.js:

    var _NSCaseId;
    var nsId;
    $("#listOfCases li").click(function(){
                nsId = $(this).attr('id');
                LocalStorage.save(_NSCaseId, nsId);
                alert(nsId);
            });
    

    As you can see, the value is the id of a listview item. This works fine and the alert shows the correct value every time.

    I then want to use the same variable in the editCase.js file:

    var id = LocalStorage.get(_NSCaseId);
        alert(id);
    

    But I get an error in logcat saying _NSCaseId is undefined in editCase.js

    Any suggestions?

  • MrJR
    MrJR over 10 years
    still getting undefined when I try to get it. :/
  • tymeJV
    tymeJV over 10 years
    Are you on a browser that supports DOM storage?
  • MrJR
    MrJR over 10 years
    it's a phonegap app running on android. It's using chrome
  • MrJR
    MrJR over 10 years
    i want to use two different javascript classes. That's why I didn't post my own jsfiddle
  • tymeJV
    tymeJV over 10 years
    The two different classes is irrelevant as localStorage will be accessible by both of them