Last active
May 2, 2017 14:24
-
-
Save remy/22e6a113a436d4f3d66d584936df7fdb to your computer and use it in GitHub Desktop.
Remembers form state on reload
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
function remember(form) { | |
var map = function (subject, fn) { | |
[].map.call(subject, fn); | |
}; | |
if (!form) { | |
[].map(document.forms, remember); | |
return; | |
} | |
var checkboxes = {}; | |
var store = sessionStorage; | |
function getValue(node) { | |
if (node.nodeName === 'SELECT' && node.multiple) { | |
// yay | |
if (node.selectedOptions.length) { | |
return [].map.call(node.selectedOptions, function (option) { | |
return option.value; | |
}); | |
} else { | |
return ''; | |
} | |
} else if (node.type === 'checkbox') { | |
return ',' + checkboxes[node.name].filter(function (node) { | |
return node.checked; | |
}).map(function (node) { | |
return node.value; | |
}).join(',') + ','; | |
} else { | |
return node.value; | |
} | |
} | |
for (var i = 0, field; field = form[i], i < form.length; i++) { | |
if (field.type === 'password') { | |
continue; // don't store passwords | |
} | |
if (field.type === 'checkbox') { | |
if (!checkboxes[field.name]) { | |
checkboxes[field.name] = []; | |
} | |
checkboxes[field.name].push(field); | |
} | |
// radio & checkboxes are handled differently | |
var value = store[field.name]; | |
if (field.nodeName === 'SELECT' && field.multiple) { | |
value = ',' + value + ','; | |
[].map.call(field.options, function (option) { | |
if (value.indexOf(option.value) !== -1) { | |
option.selected = true; | |
} | |
}); | |
} else if (field.type === 'checkbox' && value) { | |
field.checked = (value.indexOf(',' + field.value + ',') !== -1); | |
} else if (field.type === 'radio') { | |
field.checked = value === field.value; | |
} else { | |
field.value = value || ''; | |
} | |
field.addEventListener('change', function () { | |
store[this.name] = getValue(this); | |
}, false); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment