1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
|
const form = document.querySelector('#save-me'); function saveInputValue(e) { let savedInputs = localStorage.getItem('autosave-form-inputs'); savedInputs = savedInputs ? JSON.parse(savedInputs) : {}; if (e.target.type === "checkbox") { savedInputs[e.target.name] = e.target.checked ? "on" : "off"; } else { savedInputs[e.target.name] = e.target.value; } localStorage.setItem('autosave-form-inputs', JSON.stringify(savedInputs)); } function getInputsFromLocalStorage() { let inputs = Array.prototype.slice.call(document.querySelectorAll('[data-type="input"]')); let savedInputs = localStorage.getItem('autosave-form-inputs'); savedInputs = savedInputs ? JSON.parse(savedInputs) : {}; inputs.forEach(function (input) { if (!savedInputs[input.name]) return; if (input.type === "checkbox") { input.checked = savedInputs[input.name] === "on" ? true : false; } else if (input.type === "radio") { input.checked = savedInputs[input.name] === input.value ? true : false; } else { input.value = savedInputs[input.name]; } }) } function clearDataOnSubmit() { localStorage.clear(); } form.addEventListener('input', saveInputValue); form.addEventListener('submit', clearDataOnSubmit); getInputsFromLocalStorage();
|