如果取消选中所有子复选框,如何删除选中的复选框?
问题描述:
我有一组复选框(Sub1,Sub2,Sub3)和一个主复选框。如果检查任何子复选框,则必须检查主复选框。如果所有子复选框都未选中,则只有主复选框必须取消选中,如果至少选中一个复选框,则必须选中主复选框。我的代码如下所示。如果取消选中所有子复选框,如何删除选中的复选框?
<!DOCTYPE html>
<html>
<script type='text/javascript' src="jquery-1.10.1.js"></script>
<script type='text/javascript'>
$(window).load(function() {
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
var chk3 = $("input[type='checkbox'][value='3']");
var chk4 = $("input[type='checkbox'][value='4']");
chk2.on('change', function() {
chk1.prop('checked', this.checked);
});
chk3.on('change', function() {
chk1.prop('checked', this.checked);
});
chk4.on('change', function() {
chk1.prop('checked', this.checked);
});
});
</script>
</head>
<body>
<input type="checkbox" value="1" class="user_name">Main1
<br>
<br>
<br>
<input type="checkbox" value="2" id="one" class="user_name">sub-2
<br>
<input type="checkbox" value="3" id="one" class="user_name">sub-3
<br>
<input type="checkbox" value="4" id="one" class="user_name">sub-4
<br>
</body>
</html>
答
你可以有一个单一的点击处理程序,您可以检查是否有子项的检查
$(function() {
var $checks = $("input.user_name:not(.main)"),
$main = $('input.user_name.main');
$checks.change(function() {
$main.prop('checked', $checks.is(':checked'))
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" value="1" class="user_name main">Main1
<br>
<br>
<br>
<input type="checkbox" value="2" id="one" class="user_name">sub-2
<br>
<input type="checkbox" value="3" id="one" class="user_name">sub-3
<br>
<input type="checkbox" value="4" id="one" class="user_name">sub-4
<br>
答
您可以使用您共同user_name
类来实现这个每当change
事件对他们的情况。试试这个:
$('.user_name').change(function() {
var $checkbox = $(this);
var $siblings = $checkbox.siblings('.user_name');
if ($checkbox.is(':first-child')) {
$siblings.prop('checked', $checkbox.prop('checked'));
} else {
$siblings.first().prop('checked', $siblings.not(':first-child').length == $siblings.filter(':checked').length);
}
});
另外请注意,你有同样的id
属性,它是无效的多元素 - id
应该是唯一与文档的元素。
答
你需要实现一个OR语句。你可以彻底地或循环地做到这一点。这种解决方案是第一种类型:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src="jquery-1.10.1.js"></script>
<script type='text/javascript'>
$(window).load(function(){
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
var chk3 = $("input[type='checkbox'][value='3']");
var chk4 = $("input[type='checkbox'][value='4']");
chk2.on('change', function(){
chk1.prop('checked',(chk2.checked || chk3.checked || chk4.checked));
});
chk3.on('change', function(){
chk1.prop('checked',(chk2.checked || chk3.checked || chk4.checked));
});
chk4.on('change', function(){
chk1.prop('checked',(chk2.checked || chk3.checked || chk4.checked));
});
});
</script>
</head>
...
Hi Tushar,apt answer。如果我有另一组Main2((Sub-5,Sub-6,Sub-7))会怎么样?我们需要为另一组复选框做些什么改变。 –
@GaneshSudarsan你需要分享html结构 –
@GaneshSudarsan http://jsfiddle.net/arunpjohny/cpncz12L/2/? –