Persisting the information in form fields is a nice usability enhancement. Users do close pages unintentionally, so it’s a welcomed surprise when they return to the page to find their information intact.

This capability has always been available through AJAX/server-side databases or the use of cookies. But setting up database tables to collect incomplete submissions for each form on a site often doesn’t fit into our budgets. Cookies work great for only very small amounts of data, as they increase the size of each page request with each new piece of data.

Now, with the adoption of HTML 5 by over 80% of user’s web browsers, we have access to another technique, local storage. This allows us to use JavaScript to store individual pieces of information inside the browser’s internal database.

 

Getting the storage key

One easy way to do this is to create a storage key for each form on your site. The storage key can essentially be a modified version of the page URL.

var storageKey = location.href.split('?')[0].split('/').splice(3).join('_');

That will give us a key name similar to:

section1_subsection_pagename

 

Serializing the form data

Now that we have our storage key, we want to store all of the form field data under that key name. We can do that by serializing the form data into a string. jQuery’s serialize method does the job nicely for us. And, since we’re trying to save form data for the next page load, the best time to store the existing form field data is during the window unload event.

$(window).unload(function() {
window.localStorage.setItem(storageKey, $('#myform').serialize());
});

 

Loading the data back into the form

Unfortunately, jQuery doesn’t provide us with a deserialize function. So, I slightly modified Jack Allan’s version of a deseralize function, to deserialize the form data string and load it back into the form.

deserialize = function(query) {
    var pairs, i, keyValuePair, key, value, map = {};

    // remove leading question mark if its there
    if (query.slice(0, 1) === '?') {
        query = query.slice(1);
    }

    if (query !== '') {
        pairs = query.split('&');

        for (i = 0; i < pairs.length; i += 1) {
            keyValuePair = pairs[i].split('=');
            key = decodeURIComponent(keyValuePair[0]);
            value = (keyValuePair.length > 1) 
                    ? decodeURIComponent(keyValuePair[1]) : undefined;

            // this is the magic, loads the value into the form field
            $('input[name=' + key + ']').val(value);  
        }
    }
}

 

Protecting older browsers

Back to our point above about the 80% browser share, that’s 20% that won’t be able to make use of this feature, yet. Furthermore, it’ll throw a JavaScript error if they try.

We can prevent this by wrapping our local storage usage in a conditional, which first checks to see if the Storage module is available.

if (typeof Storage !== 'undefined') {
    deserialize(window.localStorage.getItem(storageKey));

    $(window).unload(function() {
         window.localStorage.setItem(storageKey, $('#myform').serialize());
    });
}
Tags:

Leave a Reply

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