How to use localStorage to remember form values

Since finishing my last post, I’ve been wanting to work on a way of implementing the concepts.  Let’s say you have a long form (like a job application) or a form you would be filling out a lot (like shipping/billing information).  You could use ajax to store the information server-side but let’s say you need or want to store it client-side.

Using jQuery, we can loop through all of the text boxes on the page, without really knowing how many elements are there.


[gist id=4102586 file=StoreFormValuesInLocalStorage-Part1.html]


Now that we know what’s there, let’s store the values in an array.


[gist id=4102586 file=StoreFormValuesInLocalStorage-Part2.html]


Now that the values are packaged up in an array, let’s build setters and getters around this.


[gist id=4102586 file=StoreFormValuesInLocalStorage-Part3.html]


You’ll notice that you can essentially just drop this javascript into a page with forms and it will start collecting values.  You need to be careful though.  What if your user is on a shared computer?  It will blindly leave the values for the next visit to the site.  My suggestion would be that you use a “remember me” checkbox.  That would give the user a little more control.  Alternately, you could replace localStorage with sessionStorage.  That would kill the stored values once they close the browser.

Leave a Reply

Your email address will not be published. Required fields are marked *