我们如何使用 DOM 访问单选按钮的值?
我们如何使用 DOM 访问单选按钮的值?
How can we access the value of a radio button using the DOM?
例如.我们有单选按钮:
For eg. we have the radio button as :
<input name="sex" type="radio" value="male">
<input name="sex" type="radio" value="female">
它们位于名为 form1
的表单中.当我尝试
They are inside a form with name form1
. When I try
document.getElementByName("sex").value
无论检查值如何,它总是返回男性".
it returns 'male' always irrespective of the checked value.
推荐答案
只是为了生成" Canavar 非常有用的功能:
Just to "generify" Canavar's very helpful function:
function getRadioValue(theRadioGroup)
{
var elements = document.getElementsByName(theRadioGroup);
for (var i = 0, l = elements.length; i < l; i++)
{
if (elements[i].checked)
{
return elements[i].value;
}
}
}
... 现在将这样引用:
... which would now be referenced thusly:
getRadioValue('sex');
奇怪的是,这样的东西还不是prototype.js的一部分.
Strange that something like this isn't already a part of prototype.js.
相关文章