Saving Form State with jQuery and localStorage

Recently I was working on a project that had a lot of forms each with a large number of inputs, and I was thinking how frustrated a user must feel when they’ve filled out some of a form and for whatever reason they lose that filled in data. Maybe they accidentally clicked a link in the sidebar, or closed the tab, or Firefox died for the twentieth time that day. Whatever the reason, the user then has to navigate back to that page and re-enter the information. I wondered if there was a solution for this using Javascript, and thought localStorage would be a good candidate. Most modern browsers now have a localStorage object, so unless your users are using an old version of Firefox or using IE7, they should all have support for it.

The idea I had involves using jQuery to attach an unload event to the window and store the targeted form’s contents in a JSON object. If you don’t know how localStorage works, check out this article on the Mozilla Developer blog¬†about how it works and its major shortcomings. In short, the only type you can store and retrieve is a string, which doesn’t make a whole lot of sense. That means that integers, floats, regexps, arrays, and objects need some pre-treatment before being stored in localStorage. In the instance of my plugin idea, ideally I would serialize the form and save it to localStorage. To do this, we can use the built in JSON.stringify and JSON.parse methods to convert the serialized object to a string and save it as a localStorage property, then convert it back to an object in order to loop through it. The only gotcha is when you want to store a function expression, you’re (almost) out of luck. JSON.stringify will strip them out, presumably because of potential security issues with parsing the then-stringified Javascript code. But in this context, we’re not doing anything of the sort so we’re good.

I put together a quick plugin that will store this information under whatever property name you give, or if none is given, by the form’s ID. I’ve tested it to work with the most common input types, but have not tested types such as file, range, number, etc. Most of the HTML5 input types should work fine, but for now I’ll only guarantee that it will work with text, hidden, checkbox, radio, select, and textarea form fields. I’ve also written it to prompt the user before it fills in the saved data, so if multiple people are using the same computer or if you really did intend to destroy the partially filled form, you don’t have to restore the form’s state.

You can check out a demo page, download the uncompressed source or grab a packed version for use on your own forms. You can also grab the uncompressed source along with the qUnit tests on GitHub.

Notes

  1. shaneriley posted this