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

查看:119
本文介绍了在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.

推荐答案

你可以使用文件.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天全站免登陆