Skip to content

Instantly share code, notes, and snippets.

@NickBeeuwsaert
Created April 1, 2016 03:27
Show Gist options
  • Save NickBeeuwsaert/87c5a9fa4f5230616e9819036f50f3b5 to your computer and use it in GitHub Desktop.
Save NickBeeuwsaert/87c5a9fa4f5230616e9819036f50f3b5 to your computer and use it in GitHub Desktop.
Serialize a element containing form controls
export function serialize(element) {
// I could probably use form.elements here
// But I want this to work if elements are just in a div
const controls = Array.from(element.querySelectorAll("input, textarea, select, button"));
const withoutName = (control) => !!control.name;
const disabled = (control) => !control.disabled;
const removeFiles = (control) => !control.matches('input[type="file"]');
const checkboxes = (control) => control.matches('input[type="checkbox"], input[type="radio"]')?control.checked:true;
const selectedOptions = (option) => option.selected;
// special handing for select elements
const serSelect = function(select) {
return Array.from(select.options)
.filter(selectedOptions)
.filter(disabled)
.map(option => [select.name, option.value]);
};
const ser = function(control){
if(control.matches("select")) return serSelect(control);
return [[control.name, control.value]];
};
return [].concat(...controls
.filter(withoutName)
.filter(disabled)
.filter(checkboxes)
.filter(removeFiles)
.map(ser));
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment