Last active
September 2, 2019 16:00
-
-
Save LB-Digital/f28f1297f1d87634fd27562e88a5f72c 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
/*------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