如果未选中另一组中的复选框,如何禁用一组复选框
How to disable a group of checkboxes if no checkbox in the other group is selected
我想这很简单,但不幸的是,我根本不知道JavaScript,无法找到一个已经存在的解决方案。
<input type='checkbox' class='group1' name='1'> Name1<br>
<input type='checkbox' class='group1' name='2'> Name2<br>
<input type='checkbox' class='group1' name='3'> Name3<br><br>
<input type='checkbox' class='group2' name='4'> Name4<br>
<input type='checkbox' class='group2' name='5'> Name5<br>
因此,如果Name1
、Name2
、Name3
均未选中,则Name4
、Name5
应禁用。
提前感谢各位!
由于我的页面已经包含jQuery到它的
- 我忘了提到禁用复选框应该显式地设置为未选中。在当前的实现中,当我选择第二组中的一个复选框(例如,
在这个页面上,我有另一个jQuery脚本,当用户选择一个名为"Check all"的复选框时,自动选择第一组的所有复选框。
<input type='checkbox' id='maincb'> Check all
Name4
),然后取消选中第一个复选框中的所有复选框时,Name4
变得禁用,但仍然选中。这是完全错误的,因为处理表单的服务器将接受Name4
作为所选选项。如果不正确,用户可能会感到困惑。和JavaScript for this:
<script type="text/javascript">
$(document).ready( function() {
$("#maincb").click( function() {
if($('#maincb').attr('checked')) {
$('.group1:enabled').attr('checked', true);
} else {
$('.group1:enabled').attr('checked', false);
}
});
});
</script>
问题是,这两个脚本不能很好地配合。即使在我将类group1
分配给复选框'Check all'之后,它也不会影响第二组的复选框。
你想这样工作吗?
http://jsfiddle.net/steelywing/MtDLB/1/
$('#check_group1').click(function () {
$('.group1:enabled').prop('checked', $(this).prop('checked'));
updateButton();
});
function updateButton() {
if ($('.group1:checked').length == 0) {
$('.group2')
.prop('disabled', true)
.prop("checked", false);
} else {
$('.group2').prop('disabled', false);
}
}
$('.group1').change(function () {
updateButton();
});
updateButton();
HTML
<input type='checkbox' class='group1' name='1'> Name1<br>
<input type='checkbox' class='group1' name='2'> Name2<br>
<input type='checkbox' class='group1' name='3'> Name3<br><br>
<input type='checkbox' class='group2' name='4'> Name4<br>
<input type='checkbox' class='group2' name='5'> Name5<br>
JavaScript(纯JavaScript,不含jQuery)
function checkFields() {
var inputs = document.getElementsByTagName('input');
if (inputs.length == 5) {
if (inputs[0].checked == true || inputs[1].checked == true || inputs[2].checked == true) {
inputs[3].disabled = false;
inputs[4].disabled = false;
}
else {
inputs[3].disabled = true;
inputs[4].disabled = true;
}
}
}
// On-load
checkFields();
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener('click', function() {
checkFields();
});
}
可能会将初始的checkFields();
放入<body onload="">
。还要记住,您希望将document.getElementsByTagName('input');
定位在具有ID的父包装器上,以避免意外地匹配页面上的其他输入字段。