description

using-localStorage-to-save-form-type-user
=========================================

using-localStorage-to-save-form-type-user

Saving Form Values in Local Storage

Here’s the fun part. Let’s say we have a basic form whose results we want to store locally. 
Whether they’re ultimately passed to a server is irrelevant. For now, 
we just want to grab the field values and create a new “entry” into our lame psuedo database.
Create a Unique ID
In order to associate each new submission with a unique ID, 
we need to first create the ID. We’ll reserve lastID for this.
We cannot have a null value for the ID when starting the app, because a null value cannot be incremented. 
This is only an issue at the onset. So we test for null, and if true, assign it a value of zero. From then out, 
until the local storage data is destroyed, we’re good to go.

Saving the Form Data
Using our very bestest friend jQuery, we’re going to grab the values of the form, create an object, 
stringify it into JSON with the ID incorporated, save to local storage, increment the ID, 
and then reload the form. Here is the function I created to do this, 
which could probably be improved upon if there are any true JavaScript/jQuery experts willing to help. 
(Note I used the jQuery form validation plugin in my project, so I left it here for posterity. 
This is not required, naturally.)
Once this function completes, a new key is created with a new ID, and the associated value is a short bit of JSON holding the aggregate form information.

Reading the Information Back

All of this is useless unless you’re going to take advantage of the data. 
The simplest example is to read the records back as a table to quickly view a history of form submissions, 
so that’s what we’ll cover.

You’ll notice in the HTML above, we had an empty table. 
You will also have noticed that in the form submission function above we called the loadHistory() 
function before we incremented. (The timing of this is important. In its current location, 
the function will load all records, but if we loaded the history after we incremented, 
then the last record would be blank because there would be no value yet for that new ID. God I hope that makes sense.)

For this example, we’re going to use the galactically awesome jQuery JSON plugin, 
which simplifies the parsing of JSON data to the point where even morons like me can get it right.