简体   繁体   English

使用JavaScript变量设置选中的单选按钮

[英]Set Checked Radio Button Using a JavaScript Variable

Is there a way to set the checked radio button using a JavaScript variable? 有没有办法使用JavaScript变量设置选中的单选按钮? I was hoping I could get the radio button by ID and update the checked radio. 我希望我可以通过ID获取单选按钮并更新已检查的无线电。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
<script>
var shirtColor = "green";

document.getElementById(shirtColor); 
</script>
</head>

<body>
<p>Shirt Color:
<input type="radio" name="shirtColor" id="red" value="red" />
Red
<input type="radio" name="shirtColor" id="green" value="green" />
Green
<input type="radio" name="shirtColor" id="blue" value="blue" /> 
Blue</p>
</body>
</html>

Just set its checked property to true : 只需将其checked属性设置为true

document.getElementById(shirtColor).checked = true;

Here's the fiddle: http://jsfiddle.net/akkSY/ 这是小提琴: http//jsfiddle.net/akkSY/

It would look like that 看起来就像那样

btn = document.getElementById("itsID");
btn.checked = true;

you can use jquery in this way 你可以用这种方式使用jquery

$("control_id").attr("checked",true);

be sure that element is loaded before this jquery is executed.. to be safe you should always put scripts in the end of the page before </body> tag 确保在执行此jquery之前加载了元素..为了安全起见,您应该始终在</body>标记之前将脚本放在页面的末尾

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM