Skip to content

Instantly share code, notes, and snippets.

@itsabdessalam
Last active February 18, 2020 07:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsabdessalam/f0506a6f0517db8049eee2252bbc35ce to your computer and use it in GitHub Desktop.
Save itsabdessalam/f0506a6f0517db8049eee2252bbc35ce to your computer and use it in GitHub Desktop.
getFormData - Helper to retrieve fields of a form as an object
/**
* 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