Using HTML5 localStorage on a form
Update – 24th April 2012
Based on the great comments recieved, the demo and download files have been updated to work using .change so it works with fields which are filled via auto fill or content pasted in.
HTML5 localStorage provides us with the ability to store named key/value pairs locally within a users browser, this means that the data stored in localStorage is still there even after a user has closed the browser, deleted their cookies or turned off their machine/device.
The HTML5 localStorage attribute is supported by most modern browsers including Firefox 3.5+, Chrome 4+, Safari 4+, Mobile Safari, Android 2+ and Internet Explorer 8+.
Now lets dive into some code and create a basic working example. In this example we are going to create a simple form which stores the data entered into the form so that if the form isn’t submitted but the browser is closed the data is still store and then retrieved when the user returns to the form.
So first we need a form for the user to fill in, here is the HTML for that:
<form id="localStorageTest" method="post" action=""> <label>Name:</label> <input type="text" name="name" id="name" class="stored" value="" /> <label>Email:</label> <input type="email" name="email" id="email" class="stored" value="" /> <label>Message:</label> <textarea name="message" id="message" class="stored"></textarea> <input type="submit" class="demo-button" value="Submit" /> </form>
The main things to notice on this form is that the form elements have been given a class of stored, this will be used to allow us to specify which fields to store as you may not want to store all the data a user inputted.
Next up is the jQuery:
OK so lets explain what is happening above, a function called init is ran when the page is first loaded. This function checks if any data is stored for each field and if so adds the data to the relevant form element.
Next we have the keyup function which runs when a user presses a key in any form element with the class of stored. This function then adds the inputted data into the localStorage.
Finally we come to submit function which when runs a user submits. This function then removes all of the data from localStorage.