Created
November 11, 2016 13:12
-
-
Save lucalanca/55e5b89ca63ecb28c4a53e1455059dca to your computer and use it in GitHub Desktop.
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
'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