[英]JQuery Checking and Unchecking Checkboxes validations
I have some checkboxes in which one is select all and other child checkboxes are there 我有一些复选框,其中一个是“全选”,其他的是子复选框
this is my html 这是我的HTML
<label> Select All </label>
<input type="checkbox" name="all" checked="" id="parent">
<label> Child 1 </label>
<input type="checkbox" name="child" checked="" id="child">
<label> Child 2 </label>
<input type="checkbox" name="child" checked="" id="child">
This is my JQuery Script of checking and unchecking 这是我检查和取消检查的JQuery脚本
$('#parent').on('change', function () {
$('.child').prop('checked', $(this).prop('checked'));
});
$('.child').on('change', function () {
$('#parent').prop('checked', false);
$('.child').not(this).prop('checked', false);
$(this).prop('checked',true);
});
The select all works fine but the ('.child') on change the parent is unchecked and the child remains checked, i cant uncheck 全选工作正常,但('.child')更改父级未选中,子级保持选中状态,我无法取消选中
I need a way to for once any child is checked the parent should be unchecked along with all other child elements but also I should be able to select multiple children 我需要一种方法来检查所有子级,然后取消选中父级以及所有其他子级元素,但我也应该能够选择多个子级
You can use click
instead of change
. 您可以使用click
而不是change
。 Also change the id="child"
to class="child"
. 还要将id="child"
更改为class="child"
。
HTML: HTML:
<label> Select All </label>
<input type="checkbox" name="all" checked="" id="parent">
<label> Child 1 </label>
<input type="checkbox" name="child" checked="" class="child">
<label> Child 2 </label>
<input type="checkbox" name="child" checked="" class="child">
JS: JS:
$('#parent').on('click', function () {
$('.child').prop('checked', $(this).prop('checked'));
});
$('.child').on('click', function () {
console.log($('.child').is(':checked').length);
if ($('.child:checked').length == 2) {
$('#parent').prop('checked', true);
} else {
$('#parent').prop('checked', false);
}
});
$('#parent').on('click', function () { $('.child').prop('checked', $(this).prop('checked')); }); $('.child').on('click', function () { if ($('.child:checked').length == 2) { $('#parent').prop('checked', true); } else { $('#parent').prop('checked', false); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label> Select All </label> <input type="checkbox" name="all" checked="" id="parent"> <label> Child 1 </label> <input type="checkbox" name="child" checked="" class="child"> <label> Child 2 </label> <input type="checkbox" name="child" checked="" class="child">
I think when you are de-selecting the child checkbox again the first function is excuting and making the parent as selected. 我认为当您再次取消选择子复选框时,第一个功能是执行,并使父项处于选中状态。 so you can try this: 因此您可以尝试以下操作:
$('#parent').on('change', function () {
if($(this).is(":checked")){
$('.child').prop('checked', $(this).prop('checked'));
}else{
$(this).prop('checked', false);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.