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.

3
  • 1
    You are trying to store an object, not JSON. It will work if you properly convert the object to and from JSON. Commented Nov 19, 2012 at 0:13
  • Thanks for your answers! @Bankzilla, how do I do it? Commented Nov 19, 2012 at 0:17
  • 1
    click the checkmark next to the answer that is correct. Commented Nov 19, 2012 at 0:18

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That worked! I tried to use JSON.stringify before but didn't know about JSON.parse....that's why it wasn't working...
Thaks! This is what I need and I found it for just 4 seconds :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.