Skip to content

Instantly share code, notes, and snippets.

@muzfr7
Last active April 30, 2023 17:13
Show Gist options
  • Save muzfr7/7e15582add46e74dee111002ec6cf594 to your computer and use it in GitHub Desktop.
Save muzfr7/7e15582add46e74dee111002ec6cf594 to your computer and use it in GitHub Desktop.
Saving form data in localStorage before page refreshes and load it back when page is loaded
/*
* Note:
* LocalStorage is kept indefinitely. Something to consider when data privacy is concern
*/
// 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());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment