A Pen by Gary Bishop on CodePen.
Created
January 3, 2019 18:31
-
-
Save gbishop/bd9a64d79556247411f7265b7fb21899 to your computer and use it in GitHub Desktop.
Autosave and restore
This file contains hidden or 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
<html> | |
<head> | |
<title>test</title> | |
</head> | |
<body> | |
<h1>testing</h1> | |
<form action="" id="myform" data-key="test"> | |
<input name="Q1" type="text" /> | |
<input name="Q2" type="checkbox" /> | |
<select name="Q3"> | |
<option value="">select</option> | |
<option value="1">1</option> | |
<option value="2">2</option> | |
</select> | |
<textarea name="Q4"></textarea> | |
</form> | |
</body> | |
</html> |
This file contains hidden or 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
window.addEventListener('load', e => { | |
console.log('load'); | |
const myform = document.getElementById('myform'); | |
if (myform instanceof HTMLFormElement) { | |
const key = 'mypoll-' + myform.dataset['key']; | |
// save all values when any change | |
myform.addEventListener('change', e => { | |
const values = {}; | |
for(f of myform.elements) { | |
if (f.name) { | |
values[f.name] = ['checkbox', 'radio'].includes(f.type) ? +f.checked : f.value; | |
} | |
} | |
localStorage[key] = JSON.stringify(values); | |
}); | |
// restore values on load | |
const values = JSON.parse(localStorage[key]); | |
for (f of myform.elements) { | |
if (f.name) { | |
if (['checkbox', 'radio'].includes(f.type)) { | |
f.checked = values[f.name] == 1; | |
} else { | |
f.value = values[f.name]; | |
} | |
} | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment