Skip to content

Instantly share code, notes, and snippets.

@gbishop
Created January 3, 2019 18:31
Show Gist options
  • Save gbishop/bd9a64d79556247411f7265b7fb21899 to your computer and use it in GitHub Desktop.
Save gbishop/bd9a64d79556247411f7265b7fb21899 to your computer and use it in GitHub Desktop.
Autosave and restore
<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>
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