开发者

Accessing radio elements in forms in javascript

开发者 https://www.devze.com 2023-01-15 23:25 出处:网络
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 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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消