kal
kal

Reputation: 29351

Accessing radio elements in forms in javascript

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.

Upvotes: 0

Views: 5224

Answers (2)

Daniel Vandersluis
Daniel Vandersluis

Reputation: 94133

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/.

Upvotes: 3

Marc B
Marc B

Reputation: 360602

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.

Upvotes: 1

Related Questions