在 JavaScript 中,如何获取页面中具有给定名称的所有单选按钮? [英] In JavaScript, how can I get all radio buttons in the page with a given name?

查看:13
本文介绍了在 JavaScript 中,如何获取页面中具有给定名称的所有单选按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所说,在 JavaScript 中获取所有单选按钮的最佳方式是什么?具有给定名称的页面?最终我将使用它来确定选择了哪个特定的单选按钮,所以用另一种方式来表达这个问题:

Like the title says, what's the best way in JavaScript to get all radio buttons on a page with a given name? Ultimately I will use this to determine which specific radio button is selected, so another way to phrase the question:

给定 JavaScript 中的字符串变量,我如何知道当前选择了哪个带有该字符串的确切单选按钮输入元素(如果有),因为它的名称是?

Given a string variable in JavaScript, how can I tell which exact radio button input element (if any) with that string as it's name is currently selected?

使用 jQuery.如果您想提供 jQuery 答案,请继续.其他人可能会发现它很有用.但这对我没有帮助,我也不会投票.

I'm not using jQuery. If you want to provide a jQuery answer, go ahead. Someone else might find it useful. But it won't help me and I won't upvote it.

推荐答案

您可以使用 document.getElementsByName(),传递无线电组的名称,然后遍历它们检查 已检查 属性,例如类似:

You can use document.getElementsByName(), passing the name of the radio group, then loop over them inspecting the checked attribute, e.g. something like:

function getCheckedValue( groupName ) {
    var radios = document.getElementsByName( groupName );
    for( i = 0; i < radios.length; i++ ) {
        if( radios[i].checked ) {
            return radios[i].value;
        }
    }
    return null;
}

这篇关于在 JavaScript 中,如何获取页面中具有给定名称的所有单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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