Last active
April 30, 2023 17:13
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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