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
Select a radio button dynamically
提问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");
回答by jabclab
You're setting the checked
attribute on the innerHTML
attribute, not on the DOM element itself; this should do the trick:
您在checked
属性上设置innerHTML
属性,而不是在 DOM 元素本身上;这应该可以解决问题:
document.getElementById("id").checked = true;