Store the data of form fields inline so it can be reverted.
Option name | Type | Description |
---|---|---|
module | helper/store-form-data.js |
formData.store(el);
formData.revert(el);
Find all the form elements inside a given element and run a callback on each.
Option name | Type | Description |
---|---|---|
el | Element | |
cb | Function |
function findAll(el, cb) {
var inputs = el.querySelectorAll('input, select, textarea');
var i = 0;
var len = inputs.length;
for (; i < len; i++) {
cb(inputs[i]);
}
}
return {
Find all the form elements inside a given element and store their current
value as a data attribute.
Option name | Type | Description |
---|---|---|
el | Element |
store: function(el) {
findAll(el, function(input) {
var name = input.nodeName.toLowerCase();
var value;
switch (name) {
case 'select':
value = input.selectedIndex;
break;
default:
value = encodeURI(input.value);
break;
}
input.setAttribute('data-stored-value', value);
});
},
Revert all the form elements inside of a given element.
Option name | Type | Description |
---|---|---|
el | Element |
restore: function(el) {
findAll(el, function(input) {
var name = input.nodeName.toLowerCase();
var value = input.getAttribute('data-stored-value');
// No stored value
if (!value && value !== '') {
return;
}
switch (name) {
case 'select':
input.options[value].selected = true;
break;
default:
input.value = decodeURI(value);
break;
}
input.removeAttribute('data-stored-value');
});
},
Clear the stored data on all the form elements inside of a given element.
Option name | Type | Description |
---|---|---|
el | Element |
clear: function(el) {
findAll(el, function(input) {
input.removeAttribute('data-stored-value');
});
}
};
}));