Skip to content

Instantly share code, notes, and snippets.

@mortenson
Created January 14, 2023 18:45
Show Gist options
  • Save mortenson/40c8468bd00d2ed4bf7065540213e75c to your computer and use it in GitHub Desktop.
Save mortenson/40c8468bd00d2ed4bf7065540213e75c to your computer and use it in GitHub Desktop.
Minimal form autosave functionality using vanilla JS
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