tags:

views:

440

answers:

4

Say I have a function similar to this:

  function getGroupValue(group)
  {
     for (var i=0; i < group.length; i++) 
     {
        if (group[i].checked) 
        {
           return group[i].value;
        }
     }
  }

that i can call with something like getGroupValue(document.forms[0].myGroup)

How do I convert this to just passing in the name of a html radio button group like getGroupValue('myGroupName') ?

A: 

It's easier to give all the radio buttons a common "group" class name, and use a CSS selector (jQuery, Prototype), then loop through the returned results and grab the name for each.

Diodeus
A: 

You could do a document.getElementsByName([GroupName]) and get the collection that way. If there are multiple groups, you can store the group name in a variable and have it pass just as you are doing now.

achinda99
+1  A: 

This should work:

 function getGroupValue(group)
 {
 var g = document.getElementsByName(group);

 for (var i=0; i < g.length; i++) 
 {
    if (g[i].checked) 
    {
       return g[i].value;
    }
 }
 }
brendan
+1  A: 

I'm assuming there's only one form on your page, given the way you were originally calling the function. If that's a valid assumption to make, then you can do the following:

function getGroupValue(groupName)
{
  var group = document.forms[0][groupName];
  for (var i = 0, n = group.length; i < n; i ++)
  {
    if (group[i].checked)
    {
      return group[i].value;
    }
  }
}

Javascript lets you specify attributes/children of the form using the brackets, so you can just use the groupName you passed in as a child of the form itself.