KSHMR
KSHMR

Reputation: 809

Storing values in localStorage via Javascript

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.

Upvotes: 0

Views: 685

Answers (2)

Oscar Jara
Oscar Jara

Reputation: 14187

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');
}

Upvotes: 0

oliakaoil
oliakaoil

Reputation: 1679

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];
    }
  }
}

Upvotes: 1

Related Questions