最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Using Javascript, How to get number of items of radio button with the same id in html - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

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

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论