Last active
February 18, 2020 07:24
-
-
Save itsabdessalam/f0506a6f0517db8049eee2252bbc35ce to your computer and use it in GitHub Desktop.
getFormData - Helper to retrieve fields of a form as an object
This file contains hidden or 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
/** | |
* Helper to retrieve fields of a form as an object | |
*/ | |
export const getFormData = form => { | |
if (!form || form.tagName !== "FORM") { | |
return; | |
} | |
const { elements } = form; | |
const data = {}; | |
const allowedTags = ["INPUT", "TEXTAREA", "SELECT"]; | |
const excludedInputTypes = ["button", "reset", "submit"]; | |
[].slice | |
.call(elements) | |
.filter(node => allowedTags.indexOf(node.tagName) !== -1 && node.name) | |
.forEach(node => { | |
if ( | |
node.tagName === "INPUT" && | |
excludedInputTypes.indexOf(node.type) === -1 | |
) { | |
if ( | |
(node.type !== "radio" && node.type !== "checkbox") || | |
(node.type === "radio" && node.checked) | |
) { | |
data[node.name] = node.value; | |
} | |
if (node.type === "checkbox") { | |
data[node.name] = node.checked; | |
} | |
} | |
if (node.tagName === "TEXTAREA") { | |
data[node.name] = node.value; | |
} | |
if (node.tagName === "SELECT") { | |
const hasOption = | |
node.options.length && node.options[node.selectedIndex]; | |
data[node.name] = hasOption | |
? node.options[node.selectedIndex].value | |
: ""; | |
} | |
}); | |
return data; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment