0

I have a use case where the the number of radio buttons can be 1 or more, what is the best practice to check

i.e

var radioElements = document.forms["formname"].elements["abc"];
for(var i=0; i < radioElements.length; i++) {
    if(radioElements[i].checked) {
        alert("blah..");
        break;
    }
}

This works when the DOM has

<form name="formname">
  <input type=radio name=abc id=abc value=aaa/>
  <input type=radio name=abc id=abc value=bbb/>
</form>

But fails to work when it has only one radio element

<form name="formname">
  <input type=radio name=abc id=abc value=aaa/>
</form>

How can I make the above javascript work in both these cases.

kal
  • 28,545
  • 49
  • 129
  • 149

2 Answers2

3

You could use getElementsByName. This method always returns a collection which you can iterate over:

var radioElements = document.getElementsByName("abc");
for(var i=0; i < radioElements.length; i++)
{
    if(radioElements[i].checked) 
    {
        alert("blah..");
        break;
    }
}

See an example of this in action at jsfiddle.net/L6SKx/.

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
1

You're accessing the radio buttons wrong:

var radios = document.forms['formname'].abc;
for (var i = 0; i < radios.length; i++) {
    if (radios[i].checked) {
       alert('#' + i + ' is checked, with value ' + radios[i].value);
    }
}

As well, with your multiple radio button example, it's invalid to have the same ID on two or more separate DOM elements. An ID has to be unique on the page.

Daniel Vandersluis
  • 91,582
  • 23
  • 169
  • 153
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • 1
    This won't still work if there is only one radio button as the radios will contain that one element and not array. – jira Sep 14 '10 at 19:15