我们如何使用 DOM 访问单选按钮的值? [英] How can we access the value of a radio button using the DOM?

查看:22
本文介绍了我们如何使用 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.

这篇关于我们如何使用 DOM 访问单选按钮的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆