Created
April 1, 2016 03:27
-
-
Save NickBeeuwsaert/87c5a9fa4f5230616e9819036f50f3b5 to your computer and use it in GitHub Desktop.
Serialize a element containing form controls
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
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