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']; f
Solution 1:
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/.
Solution 2:
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.
Post a Comment for "Accessing Radio Elements In Forms In Javascript"