Skip to content

Instantly share code, notes, and snippets.

@remy
Last active May 2, 2017 14:24
Show Gist options
  • Save remy/22e6a113a436d4f3d66d584936df7fdb to your computer and use it in GitHub Desktop.
Save remy/22e6a113a436d4f3d66d584936df7fdb to your computer and use it in GitHub Desktop.
Remembers form state on reload
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