How to reload current page without losing any form data?
This answer was extremely helpful to me, and saves the trouble of going through each field manually:
Using jQuery to store the state of a complicated form
You can use various local storage mechanisms to store this data in the browser such as the Web Storage API, IndexedDB and WebSQL (deprecated) (and UserData with IE).
The simplest and most widely supported is Web Storage 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.
Replace "localStorage
" with "sessionStorage
" in the code above if you want to store data only temporary.
I modified K3N's code to work for my purpose, and I added some comments to help others figure out how sessionStorage works.
<script>
// Run on page load
window.onload = function() {
// If sessionStorage is storing default values (ex. name), exit the function and do not restore data
if (sessionStorage.getItem('name') == "name") {
return;
}
// If values are not blank, restore them to the fields
var name = sessionStorage.getItem('name');
if (name !== null) $('#inputName').val(name);
var email = sessionStorage.getItem('email');
if (email !== null) $('#inputEmail').val(email);
var subject= sessionStorage.getItem('subject');
if (subject!== null) $('#inputSubject').val(subject);
var message= sessionStorage.getItem('message');
if (message!== null) $('#inputMessage').val(message);
}
// Before refreshing the page, save the form data to sessionStorage
window.onbeforeunload = function() {
sessionStorage.setItem("name", $('#inputName').val());
sessionStorage.setItem("email", $('#inputEmail').val());
sessionStorage.setItem("subject", $('#inputSubject').val());
sessionStorage.setItem("message", $('#inputMessage').val());
}
</script>
Find this on GitHub. Specially created for it.
https://gist.github.com/zaus/4717416