A DOM friendly way of getting values from radio buttons

The problem with radio buttons is they don’t work like ordinary form elements. You can’t just apply an ID to a radio group, use document.getElementById() to get a reference to it and then query the value. This means to find the value of my radio group I’ve had to use the old fashioned document.forms[0].groupName method to get a reference to the radio group and then cycled through each one to see which was selected.

I really don’t like using document.forms[] because it means I either have to name my forms, pass more information into my javascript function or risk having my script break if the forms on the page are reorganised. It just doesn’t feel elegant or future-friendly.

Fortunately, today I discovered you can access all the buttons in a radio group through the DOM using getElementsByName() much in the same way you’d use getElementsByID(). It’s even W3C standard compliant. Yay! :)

  1. function getRadioValue(groupName) {
  2.  var group = document.getElementsByName(groupName);
  3.  if(group.length) {
  4.   for(var x=0; x<group.length; x++) {
  5.    if(group[x].checked) {
  6.     return group[x].value;
  7.    }
  8.   }
  9.  } else if(group.checked) {
  10.   return group.value;
  11.  }
  12.  return null;
  13. }

Reference:
getElementsByName() MSDN documentation

Posted on 17 Nov 04 by Helen Emerson (last updated on 17 Nov 04).
Filed under Javascript