Created
August 2, 2022 12:42
-
-
Save psynt/8cd56f98dee1050062577b137dfcdb33 to your computer and use it in GitHub Desktop.
Autosaving forms
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
//call fieldUpdate() as the handler for oninput on your form | |
function fieldUpdate(){ | |
const formData = {}; | |
const inputs = Array.of(...document.querySelectorAll("input")).filter(it => it.type !== "submit") | |
inputs.forEach(it => formData[it.id || it.name] = it.value) | |
window.localStorage.setItem("formData", JSON.stringify(formData)) | |
} | |
function load(){ | |
const formData = JSON.parse(window.localStorage.getItem("formData")) | |
const fields = Object.entries(formData) | |
.map( ([k,v]) => { | |
id = document.getElementById(k); | |
return [id ? id : Array.of(...document.querySelectorAll(`input[name="${k}"]`)), v] | |
}) | |
fields.forEach( ([elems, value]) => elems.forEach(elem => elem.value = value) ) | |
} | |
load(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment