Thomas Hardy

Using HTML5 localStorage on a form

Update – 24th April 2012

Based on the great comments recieved, the demo and download files have been updated to work using .change so it works with fields which are filled via auto fill or content pasted in.

HTML5 localStorage provides us with the ability to store named key/value pairs locally within a users browser, this means that the data stored in localStorage is still there even after a user has closed the browser, deleted their cookies or turned off their machine/device.

The HTML5 localStorage attribute is supported by most modern browsers including Firefox 3.5+, Chrome 4+, Safari 4+, Mobile Safari, Android 2+ and Internet Explorer 8+.

Now lets dive into some code and create a basic working example. In this example we are going to create a simple form which stores the data entered into the form so that if the form isn’t submitted but the browser is closed the data is still store and then retrieved when the user returns to the form.

So first we need a form for the user to fill in, here is the HTML for that:

<form id="localStorageTest" method="post" action="">
    <label>Name:</label>
    <input type="text" name="name" id="name" class="stored" value="" />

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

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

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

The main things to notice on this form is that the form elements have been given a class of stored, this will be used to allow us to specify which fields to store as you may not want to store all the data a user inputted.

Next up is the jQuery:

<script type="text/javascript">
$(document).ready(function () {
    function init() {
        if (localStorage["name"]) {
            $('#name').val(localStorage["name"]);
        }
        if (localStorage["email"]) {
            $('#email').val(localStorage["email"]);
        }
        if (localStorage["message"]) {
            $('#message').val(localStorage["message"]);
        }
    }
    init();
});

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

$('#localStorageTest').submit(function() {
    localStorage.clear();
});
</script>

OK so lets explain what is happening above, a function called init is ran when the page is first loaded. This function checks if any data is stored for each field and if so adds the data to the relevant form element.

Next we have the keyup function which runs when a user presses a key in any form element with the class of stored. This function then adds the inputted data into the localStorage.

Finally we come to submit function which when runs a user submits. This function then removes all of the data from localStorage.

View Demo Download Demo

30 Comments

  1. ido

    Very nice. I wrote some code for a similar purpose a few days ago and I think init() can be made more flexible this way:

    var input_name = ”;
    init() {
    $.each( $(‘form input’), function() {
    input_name = $(this).attr(‘name’);
    if (localStorage[input_name]) {
    $(this).val(localStorage[input_name]);
    }
    });
    }

    This way you can have as many input fields you’d like (as long as each has a unique name attribute). What do you think?

  2. Thomas Hardy

    @ido looks like it should work fine. If I get a chance I will implement it and update the example.

  3. ivascu

    it doesn’t work with autofill :P

  4. Steffen

    @ivascu is right – I can’t make it work with autofill either. Other than that, great work!

  5. Greg Babula

    Great post, nice to see an easy implementation

  6. Chip Cullen

    Just a thought on the auto-fill issue (saw that as well) instead of using the keyup event handler, why not ‘change’? http://api.jquery.com/change/ I’m not sure – it may capture data put in by auto fill.

  7. Bryan

    If you move the .keyup code into a function and call that function in .keyup as well as .blur, it should work with autofill.

  8. Taai

    I don’t know about you, but on my Crome browser the autocomplete works just fine. Or with “autofill” you mean something else?

  9. Peter

    Very nice example! Looks very easy :-)

  10. Taai

    Ok, got it! Try to write something and select one text from autocomplete and then refresh the page – only written text will appear. So, solution would be to add extra “focusout” event. Cheers! :)

  11. Clinton Gallagher @virtualCableTV

    Apparently, the Kindle Fire browser Silk also supports localStorage

  12. Klaatu

    Also look at this article from the Opera browser people for more details on the evolving web storage standard.
    Web Storage: easier, more powerful client-side data storage
    http://dev.opera.com/articles/view/web-storage/

  13. Klaus

    Unfortunately Safari on iOS-devices has a function to delete cookies and data, and it deletes the stored data too. So you can’t delete cookies without deleting stored data …

  14. Demircan Celebi

    Thanks a lot! Like other people mentioned in the comments, I have used .change() instead of .keyup().

  15. Thomas Hardy

    Thanks a lot everyone, the demo and download will be updated to use .change() in the next few days.

    Will also be looking at changing the init function so it just picks up any input in a form.

  16. Peter Frick

    Please be aware that you’ll delete ALL stored data by calling localStorage.clear(). In my opinion it would be a good practise to clear only the fields you created.

    Also think about the naming of your keys: Fields like ‘email’ and ‘name’ are very common and could lead to confusing results. I’d suggest a prefix like ‘th-email’ or something that identifies your site. A prefix would also make it much easier to handle and clear your data.

  17. Eliza

    Thank you for your code. However, I need to be able to send the data from the form to a new page.

    I would appreciate your help with this please.

  18. Al Kirby

    Any chance someone could help implement this with Contact Form 7 WordPress plugin? I’ve added “class:stored” and “id:whatevers” to all the Contact Form 7 inputs, etc, and I also included the JS within the page.php file using the “id” of the Contact Form 7 form. Strange thing is the “id” isn’t appearing when I view source.

    http://ufcc.ufl.edu/agencies/ufcc-application-for-participation/

    thanks in advance

  19. Mike

    Thomas,
    Any chance you can update this so the init function picks up any input in a form? I am trying to accomplish this and runnign into issues. The form I am using has many fields and the code would be tedious to list each field individually.

    Thanks

  20. Braj

    Thomas,

    Great work man!

    Can you tell me one more thing. How can be traced if an image file already stored into localStorage? if there are some changes on size of the files, etc. so we can rectify that image.

    It can help us on speed up downloading the webpage once it loads.

    Thanks

  21. Joe

    this is great but when you click the button how do you transfer it into another page showing the details entered?

  22. Bendix

    Hi Thomas,

    thank you for sharing this.

    I took the code from ido above and enhanced a little bit as a self invoking function for faster initialization:

    (function() {
    $.each($(‘input,textarea’), function() {
    if(localStorage[$(this).attr('name')]) {
    $(this).val(localStorage[$(this).attr('name')]);
    }
    });
    })();

    Works fine for me. Perhaps you want to update your exampe. You also forgot to update your example with .change() in the text.

  23. Pedro Salles

    Hi! How can I get this working for storage checkbox infos? Thanks!

  24. Jose Marcos

    Thanks!!

    Great autocomplete wrapper for filling forms!

    take care!

  25. Celso Jr

    Hi Thomas,

    Thanks for sharing this idea.

    You have inspired me to write a tip on codeproject web site that has solved the limitations on your script. So I came back here to share with you hoping some one else can improve this idea even more.

    http://www.codeproject.com/Tips/627090/jsRemember

    Happy coding everyone!

    Best regards…

    Celso Jr.

  26. Gaby Ferman

    Hi, how could i retrieve the values on the form to show them on my website?

  27. Stephanie Bertha

    I tried setting this up using your instructions and demo source code, but it’s not working. I must be missing something?

  28. Glen

    Great sample. Is it possible to set it up with a separate submit button and a clear button. I am new to js and have been trying a few things but none have worked yet.

  29. Héctor Mamani

    Great! How i connect with my DB? (Base Libreoffice)

  30. Vincent

    Why is not working on my cpu ?

Leave a Comment