![](/img/trans.png)
[英]javascript enable disable radio button on click and select only one at a time
[英]javascript enable disabled checkbox on click and select only one at a time
我正在动态生成带有 chkBox100 等 id 和 onClick 函数的复选框。
我想做的是
我想在没有 jquery 或任何其他库的标准 javascript 中做到这一点。
请帮助您的帮助将不胜感激。 到目前为止,这是我的代码。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title> New Document </title>
<script type="text/javascript">
function toggle(chkBox)
{
if (chkBox.checked)
{
chkBox.checked = false;
}
else
{
chkBox.checked = true;
}
// only select one at a time.
}
</script>
</head>
<body>
<form id="myForm" name="myForm">
<input type="checkbox" id="chkBox100" onClick="toggle(this);">
<input type="checkbox" id="chkBox121" onClick="toggle(this);">
<input type="checkbox" id="chkBox1180" onClick="toggle(this);">
</form>
</body>
</html>
如果不使用库,我想您可以执行以下操作,如果我理解正确的话,它似乎可以工作。
您缺少的代码是将取消选择其余部分的代码。 为此,您应该首先获得所有复选框的列表,然后取消选择所有复选框。 然后,选择用户单击的那个。
function toggle(chkBox) {
checkboxes = document.getElementById("myForm").childNodes;
var isChecked = chkBox.checked; //this just changed, so it really is whether the box wasn't checked beforehand.
for (var i = 0; i < checkboxes.length; i++) {
checkboxes[i].checked = false; //clear all of them
}
if (isChecked) {
chkBox.checked = true; //if the original one wasn't checked, check it
}
}
这样做的另一种方法是使用单选按钮,它自动具有您想要的前两个属性,但没有第三个,尽管您可以像 RobG 所说的那样解决这个问题,另一个选项是“以上都不是”。
您是否考虑过使用带有默认选中按钮的单选按钮,这实际上是“无选择”选项? 不需要 javascript。
<input type="radio" name="rb" value="zero">Zero
<br>
<input type="radio" name="rb" value="one">One
<br>
<input type="radio" name="rb" value="two">Two
<br>
<input type="radio" name="rb" value="None" checked>None of the above
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.