在一组单选按钮中,他们的name属性相同,则这些单选按钮只有一个被选中。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>单选项</title>
<script language="javascript">
//获得被选中的值
function getChoice(){
var oForm = document.forms["myForm1"];
var aChoices = oForm.camera;
//遍历整个单选项表
for(i=0;i<aChoices.length;i++){
//如果发现了被选中项则退出
if(aChoices[i].checked)
break;
}
document.getElementById("txtResult").innerHTML="您使用的相机品牌是:"+aChoices[i].value;
}
//设置某选项被选中
function setChoice(iNum){
var oForm = document.forms["myForm1"];
oForm.camera[iNum].checked = true;
}
</script>
</head>
<body>
<form method="post" name="myForm1">
您使用的相机品牌:<br />
<input type="radio" name="camera" id="canon" value="Canon">
<label for="canon">Canon</label><br />
<input type="radio" name="camera" id="nikon" value="Nikon">
<label for="nikon">Nikon</label><br />
<input type="radio" name="camera" id="sony" value="Sony" checked>
<label for="sony">Sony</label><br />
<input type="radio" name="camera" id="others" value="其它">
<label for="others">others</label><br />
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" class="btn">
<input type="button" value="检测选中对象" onclick="getChoice();">
<input type="button" value="设置为Canon" onclick="setChoice(0);">
<p><span id="txtResult"></span></p>
</form>
</body>
</html>