Skip to content

Instantly share code, notes, and snippets.

@lucalanca
Created November 11, 2016 13:12
Show Gist options
  • Save lucalanca/55e5b89ca63ecb28c4a53e1455059dca to your computer and use it in GitHub Desktop.
Save lucalanca/55e5b89ca63ecb28c4a53e1455059dca to your computer and use it in GitHub Desktop.
'use strict';
const FIELD_TYPE_BLACKLIST = ['file', 'reset', 'submit', 'button'];
const isFieldSerializable = (field) => field.name && FIELD_TYPE_BLACKLIST.indexOf(field.type) === -1
const formFieldsReducer = (state, field) => {
if (!isFieldSerializable(field)) {
return state;
}
// exclude checkbox and radio if they are not checked
if (['checkbox', 'radio'].indexOf(field.type) > -1 && !field.checked) return state;
if (state[key] === undefined) {
return Object.assign({}, state, { [key]: field.value });
}
if (Object.prototype.toString.call(state[key]) === '[object Array]') {
return Object.assign({}, state, { [key]: state[key].concat([field.value]) });
}
return state;
}
/**
* Serializes a form domNode into an object
* @param {domNode} form the form element
* @returns {object} form data in the object format
*/
module.exports = function (form) {
const formFields = form.querySelectorAll('input:not(:disabled), textarea:not(:disabled), select:not(:disabled)');
return Array.from(formFields).reduce(formFieldsReducer, {});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment