在 JavaScript 中,如何获取页面中具有给定名称的所有单选按钮?

2022-01-21 00:00:00 radio-button 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;
}

相关文章