Created
March 12, 2024 18:43
-
-
Save Sinewyk/d82c59d6f42c7de78ce960cbf7ffa8f6 to your computer and use it in GitHub Desktop.
serialize from form element
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
/** | |
* Serialize values from a DOMNode (should probably be an input) | |
* @param {DOMNode} el The element you want to serialize | |
* @return {object} The couple { object, value } of the serialized field | |
* | |
* @note Needs an Array.from es6 polyfill | |
* because of destructuring of NodeList DOM stuff | |
*/ | |
export function serializeValueFromDOMNode(/* HTMLFormElement */ el) { | |
const name = el.name; | |
const type = el.type; | |
let value; | |
if (type === 'select-multiple') { | |
value = [...el.options].filter(option => option.selected).map(option => option.value); | |
} else if (type === 'checkbox') { | |
// if multiple checkboxes have the same name it won't return a checkbox | |
// it will return a list ... thus it should not have a type | |
// REVERSE DUCK TYPING FTW \o/ | |
if (el.form.elements[name].type !== 'checkbox') { | |
value = [...el.form.elements[name]] | |
.filter(checkBox => checkBox.checked) | |
.map(checkBox => checkBox.value); | |
} else { | |
value = el.checked; | |
} | |
} else if (el.type === "number") { | |
// case for type number ... to have value as a number ... | |
value = el.valueAsNumber; | |
} else { | |
// case for select-simple (no multiple), radio, textarea, input (text and such) | |
value = el.value; | |
} | |
return { | |
name, | |
value, | |
}; | |
} | |
// serialize whole form | |
[...someForm.elements].reduce((acc, input) => { | |
const {value,name} = serializeValueFromDOMNode(input); | |
acc[name] = value; | |
return acc; | |
}, {}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment