Skip to content

Instantly share code, notes, and snippets.

@LB-Digital
Last active September 2, 2019 16:00
Show Gist options
  • Save LB-Digital/f28f1297f1d87634fd27562e88a5f72c to your computer and use it in GitHub Desktop.
Save LB-Digital/f28f1297f1d87634fd27562e88a5f72c to your computer and use it in GitHub Desktop.
/*------EXTRACT FORM INPUTS------
* Returns Object of name:value pairs in .data
* .error will contain invalid input name on Error (e.g: empty required input)
*/
function extractFormInputs( formEl ){
// get all inputs from form
var inputs = formEl.querySelectorAll('input,textarea');
// convert inputs to array
var inputsArr = Array.from(inputs);
// reduce input name:value pairs into single Object
return inputsArr.reduce(( acc, input )=>{
if (input.type==='radio'){
// radio input
if (!Object.keys(acc.data).includes(input.name)){
// input of this name not yet stored
var allChecked = inputsArr.filter(loopInput=>{
return (
loopInput.type==='radio' &&
loopInput.name===input.name &&
loopInput.checked
);
});
if (allChecked.length > 0){
acc.data[input.name] = allChecked[0].value;
}else{
// no radio btn for this name is checked
acc.data[input.name] = null;
}
}
}else{
// other input type
acc.data[input.name] = (input.value) ? input.value : null;
}
if (
!acc.error &&
acc.data[input.name]===null &&
input.required
) { acc.error = input.name; }
return acc;
}, {
error:false,
data:{}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment