Using Javascript, How to get number of items of radio button with the same id in html;
I am aware if I can wrap a form on top of the radio button I can get the length like
document.formname.radiobtnobj.length;
Wondering if is there a way I can get the number of items if I do not have a parent form to that control.
Using Javascript, How to get number of items of radio button with the same id in html;
I am aware if I can wrap a form on top of the radio button I can get the length like
document.formname.radiobtnobj.length;
Wondering if is there a way I can get the number of items if I do not have a parent form to that control.
Share Improve this question edited Jan 12, 2010 at 18:55 Andy E 345k86 gold badges481 silver badges451 bronze badges asked Jan 12, 2010 at 18:14 RamjiRamji 2,5667 gold badges35 silver badges54 bronze badges2 Answers
Reset to default 7All IDs must be unique. Duplicating IDs is BAD HTML.
That being said, one way to do what you intend is to give all of the radio buttons a class name, and get all of the items that share that class name.
In forms we usually group radio buttons by giving them the same NAME, not ID. In this case, the elements are an array.
var myRadioButtons = document.forms[0].yourRadioButtonName // this gives you back your array.
alert(myRadioButtons[0].value)
alert(myRadioButtons[0].checked)
alert(myRadioButtons.length)
As Diodeus mentioned, use the name attribute - do not duplicate the id attribute. Then you can use document.getElementsByName()
. No <form>
necessary.
var radioGrp = document.getElementsByName(radioButtonName)[0];
Also, don't use eval()
unless you have a good reason. evaling a dom object's ID isn't one.