If you haven’t used JavaScript’s “localStorage” before – now’s the time to at least look at it.
It allows for some really simple data storage – in a way similar to cookies but much easier ( in my opinion ) to work with.
So adding an item to it is as simple as:
localStorage.setItem('checkbox-name', 'checked');
Retrieving the value, let’s say after a page refresh, is as simple as:
var checkbox_state = localStorage.getItem('checkbox-name');
Which brings us to the subject of this article.
Saving a form state
You can use the simple syntax above to store the state of a checkbox or any other input to avoid frustrating your website visitors.
I’ve found this very helpful in a cart-like page where users could select some options and further navigate the website before submitting.
Instead of having to create a back-end storage for a form state that would get discarded after submission if found it much more straight-forward to use localStorage.
Here some sample code:
m_form.on('change', '.checkbox', function(e) { var name = $(this).attr('name'); localStorage.setItem(name, $(this).is(':checked')); update_notice_message(); // An example function which you can call });
This in turn allows you to retrieve the data on page load and keep the form state. Something among the lines of:
checkboxes.each( function () { var name = $(this).attr('name'); var checked = JSON.parse(localStorage.getItem(name)); if (checked === true) { $(this).prop('checked', true); $(this).parent().addClass('selected'); } });
See how the flexibility of these methods allows us to make a form more enjoyable in just a few lines of code?