javascript 动态选择一个单选按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8357917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 03:11:16  来源:igfitidea点击:

Select a radio button dynamically

javascriptfunctionalert

提问by El Classico

I need to select a radio button dynamically.

我需要动态选择一个单选按钮。

i) I have created few radio buttons dynamically, i.e. in a function using:

i) 我动态创建了几个单选按钮,即在一个函数中使用:

function funcName()
{
    Something.innerHTML = '<input type = "radio" name = "rName" id = "1" />' + '<input   type = "radio" name = "rName" id = "2" />' + '<input type = "radio" name = "rName" id = "3" />';

}

ii) I need to select a radio button dynamically, in another function:

ii) 我需要在另一个函数中动态选择一个单选按钮:

function funcNAme(someVar)
{
    document.getElementById(someVar).checked = true;
}

But this does not work, i.e. the radio button doesn not get selected. However, 'disabled' works fine. Also:

但这不起作用,即单选按钮没有被选中。但是,“禁用”可以正常工作。还:

alert(someVar); 

returns the appropriate desired value.

返回适当的所需值。

回答by Manse

The syntax is as follows :

语法如下:

element.checked = true;

So you need to use

所以你需要使用

document.getElementById(someVar).checked = true;

See here -> HTMLInputElement

看这里 -> HTMLInputElement

Working example -> http://jsfiddle.net/p5yca/

工作示例 -> http://jsfiddle.net/p5yca/

And please please do not use numbers for IDs of elements -> http://www.w3.org/TR/html401/types.html#type-name

并且请不要使用数字作为元素的 ID -> http://www.w3.org/TR/html401/types.html#type-name

回答by Richard Dalton

Seems to work fine:

似乎工作正常:

function checkRadio(id) {
    document.getElementById(id).checked = true;
}

function createRadios()
{
    document.getElementById('container').innerHTML = '<input type = "radio" name = "rName" id = "1" />' + '<input   type = "radio" name = "rName" id = "2" />' + '<input type = "radio" name = "rName" id = "3" />';
}

createRadios();
checkRadio("2");

Example - http://jsfiddle.net/infernalbadger/LHyQT/2/

示例 - http://jsfiddle.net/infernalbadger/LHyQT/2/

回答by jabclab

You're setting the checkedattribute on the innerHTMLattribute, not on the DOM element itself; this should do the trick:

您在checked属性上设置innerHTML属性,而不是在 DOM 元素本身上;这应该可以解决问题:

document.getElementById("id").checked = true;