Created
January 14, 2023 18:45
-
-
Save mortenson/40c8468bd00d2ed4bf7065540213e75c to your computer and use it in GitHub Desktop.
Minimal form autosave functionality using vanilla JS
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
document.querySelectorAll("form").forEach((formEl) => { | |
const key = location.pathname + formEl.id; | |
const json = localStorage.getItem(key); | |
if (json) { | |
const data = JSON.parse(json); | |
Object.keys(data).forEach((inputId) => { | |
formEl.elements[inputId].value = data[inputId]; | |
}); | |
} else { | |
localStorage.setItem( | |
key, | |
JSON.stringify(Object.fromEntries(new FormData(formEl))) | |
); | |
} | |
formEl.addEventListener("input", () => { | |
localStorage.setItem( | |
key, | |
JSON.stringify(Object.fromEntries(new FormData(formEl))) | |
); | |
}); | |
formEl.addEventListener("submit", () => { | |
localStorage.removeItem(key); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment