HTML5 localStorage on a form

You can make a HTML form using HTML5 localStorage feature. Why required localStorage for form? You will not loose filled field data when refresh or close the browser, You will get same data when you back to same form page. In this example I am going to explain you how you can make HTML5 form with localStorage. You will not loose filled field values until you submit form. You can clear localStorage values when user submit form.

1) Create HTML form with four fields first name, last name, email and message.

<form id="localStorageForm" method="post" action="">
    <label>First name:</label>
    <input type="text" name="name" id="fname" class="text" value="" />

    <label>Last name:</label>
    <input type="text" name="name" id="lname" class="text" value="" />

    <label>Email:</label>
    <input type="email" name="email" id="email" class="text" value="" />

    <label>Message:</label>
    <textarea name="message" id="message" class="text"></textarea>

    <input type="submit" class="button" value="Submit" />
</form>

2) Include jQuery library in page header to use below jQuery script.

$(function (){

    function storeValues() {
        if (localStorage["fname"]) {
            $('#fname').val(localStorage["fname"]);
        }
        if (localStorage["lname"]) {
            $('#lname').val(localStorage["lname"]);
        }
        if (localStorage["email"]) {
            $('#email').val(localStorage["email"]);
        }
        if (localStorage["message"]) {
            $('#message').val(localStorage["message"]);
        }
    }

    storeValues();

    $('.text').keyup(function () {
        localStorage[$(this).attr('name')] = $(this).val();
    });

    $('#localStorageForm').submit(function() {
        localStorage.clear();
    });

});

Written jQuery for Storing all input in localStorage, update localStorage values when keyup and clear all localStorage value when successfully submit the form.

shanidkv's picture