3

Possible Duplicate:
Storing Objects in HTML5 localStorage

I'm trying to store JSON data, name & phonenumber given in two text fields and then later(after page refresh) retrieve and print the data on the same fields with following code.

        function saveData() {
            var saveD = { 
                name: document.getElementById("name").value,
                phone: document.getElementById("phone").value
            }; 

            window.localStorage.setItem("info", saveD);
        } 
        var storedData = window.localStorage.getItem("info");

        document.getElementById("name").value = storedData.name;
        document.getElementById("phone").value = storedData.phone;

What is wrong? I get "undefined" on both fields.

Community
  • 1
  • 1
Dean.V
  • 111
  • 9

1 Answers1

5

Save like this:

window.localStorage.setItem("info", JSON.stringify(saveD));

And load like this:

var storedData = JSON.parse(window.localStorage.getItem("info"));

You have to store objects as JSON in local storage.

David Müller
  • 5,291
  • 2
  • 29
  • 33