0

I've been working on this, and it's very nearly working. I have a feeling that the setInterval inside the loop is something that can't be done, or isn't working. Without the setInterval and the final 'if' statement, it loops through the elements perfectly and adds a className to each if I set it to. Here's my script if anyone can advise as to where I am going wrong:

(function() {
    var localStorageID = document.getElementById('local-storage');
    var inputTags = ['input', 'textarea', 'select', 'button'];

    // Loop through all the input tags on the page
    for(var i = 0; i < inputTags.length; i++) {

        // Create a variable that matches input tags inside our #localStorage
        var localStorageTag = localStorageID.getElementsByTagName(inputTags[i]);

        var formData = {};

        for(var z = 0; z < localStorageTag.length; z++) {
            formData[localStorageTag[z].name] = localStorageTag[z].value;
        }

        localStorage.setItem('formData', formData);

        if(localStorage.getItem('formData')) {
            // Try to achieve something
        }   
    }
})();
  • It doesn't look like you're actually using `localStorage`. Does `currentLocalTag` refer to an input element? If so, you can't run `setItem` on it. You have to use `localStorage.setItem`, where `localStorage` is on the global object. – pimvdb Feb 06 '13 at 21:29
  • Ah yes, stupid error on my behalf. –  Feb 06 '13 at 21:36
  • Does that mean the question is answered? If so, please close. – Steve H. Feb 06 '13 at 21:58
  • @SteveH. I've updated the code above with my updates. I have converted the form data to an object. Not sure if you have any ideas on finalising it! –  Feb 06 '13 at 22:03

1 Answers1

0

You cannot store objects in localStorage. They must be strings. Convert the object to a string using JSON.stringify(), then JSON.parse() the string when retrieving from localStorage.

EDIT: for example:

localStorage.setItem('formData', JSON.stringify(formData));
var fd= JSON.parse(localStorage.getItem('formData'));

if(fd) {
    // Try to achieve something
} 
Steve H.
  • 6,912
  • 2
  • 30
  • 49