How to reload current page without losing any form data?

You can use various local storage mechanisms to store this data in the browser such as Web Storage, IndexedDB, WebSQL (deprecated) and File API (deprecated and only available in Chrome) (and UserData with IE).

The simplest and most widely supported is WebStorage where you have persistent storage (localStorage) or session based (sessionStorage) which is in memory until you close the browser. Both share the same API.

You can for example (simplified) do something like this when the page is about to reload:

window.onbeforeunload = function() {
    localStorage.setItem("name", $('#inputName').val());
    localStorage.setItem("email", $('#inputEmail').val());
    localStorage.setItem("phone", $('#inputPhone').val());
    localStorage.setItem("subject", $('#inputSubject').val());
    localStorage.setItem("detail", $('#inputDetail').val());
    // ...
}

Web Storage works synchronously so this may work here. Optionally you can store the data for each blur event on the elements where the data is entered.

At page load you can check:

window.onload = function() {

    var name = localStorage.getItem("name");
    if (name !== null) $('#inputName').val("name");

    // ...
}

getItem returns null if the data does not exist.

Use sessionStorage instead of localStorage if you want to store only temporary.

Leave a Comment