Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top