Skip to content

Instantly share code, notes, and snippets.

@branneman
Last active April 22, 2016 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save branneman/52c8f0faea1f586cf75d to your computer and use it in GitHub Desktop.
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
/**
* 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