0

My objective is to store data submitted via a certain named form with one function and retrieve the data with another function. The form contains several input tags and two select tags. This is the JS code:

function storage() {
    if (typeof(Storage) != "undefined") {
        var elements = document.getElementsByTagName('input');
        for (var input in elements) {
            input.value = localStorage.getItem(input.name);
        }
        var elements = document.getElementsByTagName('select')
        for (var select in elements) {
            select.value = localStorage[select.name];
    }

    }
    alert("Success?");
}

function onSubmit() {
    inputs = document.forms["forsendur"].getElementsByTagName("input");
    selects = document.forms["forsendur"].getElementsByTagName("select");
    for (var i=0; i<inputs.length; i++) {
        localStorage.setItem(inputs[i].name, inputs[i].value);
    }
    alert("Success?");
}

This is the separate input tag that calls the storage() function:

    <input type="button" class="button2" value="Last session" onClick="storage();">

This is the (partially omitted) form:

<form action="cool_url" name="forsendur" method="post"> 
    <lots of input and select tags>
    <input class="button2" type="submit" value="Reikna" onClick="onSubmit();"/>
</form>

However, nothing happens (I can confirm that the data is being sent correctly through the form). I have included two alert() calls, which are triggered, so the functions are called and are executed.

5
  • Use the debugger (e.g. from Chrome dev tools) to check, if actually all of your code executes and which values your inputs hold. Also in the "resources" Tab you can examine your localStorage and check if the values are present. Commented Jul 11, 2014 at 16:15
  • Thanks for the reply, the values are not present. The values input are normal. Commented Jul 11, 2014 at 16:19
  • Using your exact same code, I can see it is getting stored in the localStorage, however since your example input element has no name, the key is empty and thus the value can't be retrieved in return. Additionally, another problem is your for in loop on the html collection, use a plain for loop instead, like your do in your onSubmit(). Commented Jul 11, 2014 at 16:26
  • Now I get "Uncaught Invalid State Error" (failed to set value property) in this line: elements[i].value = localStorage[elements[i].name]; Commented Jul 11, 2014 at 16:41
  • Take a look at the demofiddle - I hope this helps: jsfiddle.net/VJZ5g Commented Jul 11, 2014 at 17:04

2 Answers 2

1

There is a problem with the for loop in your storage function. You could fix it by rewriting it to match the one in your onSubmit function:

function storage() {
  if (typeof(Storage) != "undefined") {

    var elements = document.getElementsByTagName('input');
    for (var i=0; i<elements.length; i++) {
        elements[i].value = localStorage.getItem(elements[i].name);
    }

    var elements = document.getElementsByTagName('select')
    for (var i=0; i<elements.length; i++) {
      elements[i].value = localStorage[elements[i].name];
    }
  }
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the reply but I'm still doing something wrong. Problem persist :(
Here is JSFiddle. Sorry my computer is too slow to navigate JSFiddle. I hope you don't drown in this :D jsfiddle.net/3Jj7m
Unfortunately JSFiddle cannot parse your template language, so your fiddle doesn't really work.
I have one update though - the Last Session button turns to undefined when I press it. Since it itself is an input, the function must be doing something.
It works. woohoo :D My fix: I had to do elements[i].setAttribute(attributename, attributevalue) instead of what I did.
0

Well, since you are using jquery tag, I will use it in the following example I've implemented which follows the same "situation" you are trying to resolve but in other way, hope it helps since it will reduce your lines of code.

Live Demo: http://jsfiddle.net/oscarj24/3Pa6Z/


HTML: I've added one input and select to follow what you wrote in your question. You can have many of them, don't forget to add a name attribute to each element.

<form action="/echo/json/" name="form" method="post">
    <!-- Test input/select -->
    Name: <input type="text" name="name" value="Oscar" /><br>
    Gender:
    <select name="gender">
        <option value="M">Male</option>
        <option value="F">Female</option>
    </select><br>
    <!-- Test input/select -->
    <input class="btn" type="submit" value="Send" />
</form>

jQuery: Please read comments!

// Document ready handler
$(function() {
    // Get form
    var frm = $('form');

    // Form submit handler
    frm.on('submit', function() {
        // Get all form elements as javascript object
        var frmData = frm.serializeArray();

        // Check if object is not empty and if local storage
        // is available to store form data using their names and values
        if(!$.isEmptyObject(frmData) && hasStorage()) {
            for(var i = 0; i < frmData.length; ++i) {
                var elem = frmData[i];
                localStorage.setItem(elem.name, elem.value);
            }
        }
    });

    //TODO: Remove after testing
    if(hasStorage()) {
        // Print stored values, at first time 'Name' and 'Gender' will be 'null'
        console.log('Name: ' + localStorage.getItem('name'));
        console.log('Gender: ' + localStorage.getItem('gender'));

        // Remove all stored values
        localStorage.clear();
    }
});

// Used to check if localStorage feature is supported
function hasStorage() {
    return (typeof(Storage) !== 'undefined');
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.