Last active
April 22, 2016 08:36
-
-
Save branneman/52c8f0faea1f586cf75d to your computer and use it in GitHub Desktop.
getFormElementValue() - Returns the value of a form element, given it's name and type
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
/** | |
* getFormElementValue() | |
* Returns the value of a form element, given it's name and type | |
* | |
* @param {String} name - An element's `name=""` attribute | |
* @param {String} type - An element type string, e.g. 'text', 'radio', 'select' | |
* @returns {String|Boolean} | |
*/ | |
const getFormElementValue = (function(){ | |
const getElement = name => document.querySelector('[name="' + name + '"]'); | |
const getters = {}; | |
getters.text = name => getElement(name).value; | |
getters.checkbox = name => getElement(name).checked; | |
getters.radio = name => { | |
const elems = document.getElementsByName(name); | |
for (var i = 0; i < elems.length; i++) { | |
if (elems[i].checked) return elems[i].value; | |
} | |
} | |
getters.select = name => { | |
var elem = getElement(name); | |
return elem.options[elem.selectedIndex].value; | |
}; | |
return (name, type) => getters[type](name); | |
}()); | |
getFormElementValue('field-text', 'text'); //=> String (value attr) | |
getFormElementValue('field-radio', 'radio'); //=> String (value attr) | undefined | |
getFormElementValue('field-checkbox-1', 'checkbox'); //=> Boolean | |
getFormElementValue('field-checkbox-2', 'checkbox'); //=> Boolean | |
getFormElementValue('field-select', 'select'); //=> String (value attr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment