Save Form field values in case the browser tab is closed

I added a functionality to the Form plugin where the field values are saved as a cookie in case the browser tab is closed, and thought I’d share in case someone else finds it useful as well as to store the instructions on this site instead of my own messy archives :slight_smile:

  1. Add a file called localstorage.js into /user/themes/[yourtheme]/js/ with this javascript (change “name”, “email”, and “message” in the first function to whatever fields your form has, adding if clauses as needed):

—js
// Save form values to localStorage unless Submit pressed

$(document).ready(function () {
function init() {
if (localStorage[“name”]) {
$(’#name’).val(localStorage[“name”]); // Change
}
if (localStorage[“email”]) {
$(’#email’).val(localStorage[“email”]); // Change
}
if (localStorage[“message”]) {
$(’#message’).val(localStorage[“message”]); // Change
}
}
init();
});

$(’.stored’).change(function () {
localStorage[$(this).attr(‘name’)] = $(this).val();
});

$(’#localStorageTest’).submit(function() {
localStorage.clear();
});

(function( win ){
var doc = win.document;

// If there's a hash, or addEventListener is undefined, stop here
if( !location.hash && win.addEventListener ){
    //scroll to 1
    window.scrollTo( 0, 1 );
    var scrollTop = 1,
        getScrollTop = function(){
            return win.pageYOffset || doc.compatMode === "CSS1Compat" && doc.documentElement.scrollTop || doc.body.scrollTop || 0;
        },
        //reset to 0 on bodyready, if needed
        bodycheck = setInterval(function(){
            if( doc.body ){
                clearInterval( bodycheck );
                scrollTop = getScrollTop();
                win.scrollTo( 0, scrollTop === 1 ? 0 : 1 );
            }
        }, 15 );
    win.addEventListener( "load", function(){
        setTimeout(function(){
                //reset to hide addr bar at onload
                win.scrollTo( 0, scrollTop === 1 ? 0 : 1 );
        }, 0);
    } );
}

})( this );


2. Load the .js file by adding this line at the bottom of your `base.html.twig` (or whatever the base template for your form page is):

---html
<script src="{{ url('theme://js/localstorage.js') }}" type="text/javascript" ></script>
  1. Add the class .stored to all the form fields you want to store in the markdown file’s frontmatter:

—yaml

form:
fields:

classes: stored


Somebody could probably adapt the code to add a for loop to automatically store all the fields containing a .stored class, but for my limited uses this was sufficient :) 

Original code by [Thomas Hardy](http://www.thomashardy.me.uk/using-html5-localstorage-on-a-form)