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
|
const form = document.querySelector('#save-me'); function saveInputValue (e) { let savedInputs = localStorage.getItem('form-inputs'); savedInputs = savedInputs ? JSON.parse(savedInputs) : {}; savedInputs[e.target.id] = `${e.target.value}`; localStorage.setItem('form-inputs', JSON.stringify(savedInputs)); } function getInputsFromLocalStorage () { let inputs = Array.prototype.slice.call(document.querySelectorAll('[data-type="input"]')); let savedInputs = localStorage.getItem('form-inputs'); savedInputs = savedInputs ? JSON.parse(savedInputs) : {}; inputs.forEach(function(input) { if (!savedInputs[input.id]) return; input.value = savedInputs[input.id]; }) } function clearDataOnSubmit () { localStorage.clear(); } form.addEventListener('input', saveInputValue); form.addEventListener('submit', clearDataOnSubmit); getInputsFromLocalStorage ();
|