简体   繁体   English

选中父复选框的子点击复选框

[英]Check the child checkboxes onclick of parent checkbox

I have an html code where there are two parent checkboxes and their children respectively. 我有一个html代码,其中分别有两个父复选框和它们的子复选框。 Onclick of parent checkbox the children belonging to that parent should be checked. 选中父级复选框后,应选中属于该父级的子级。 In my case , if I check a parent checkbox all child checkboxes are selected. 就我而言,如果我选中一个父复选框,则所有子复选框都被选中。 I know its the problem with the classname I can name with two different class names and solve the problem. 我知道它的类名问题,我可以用两个不同的类名命名并解决问题。 But i cannot change the classnames. 但是我不能更改类名。 It should be the same. 应该是一样的。 how do I fix this?? 我该如何解决??

index.html index.html

        Parent1<input name="parent" class="pc-box" type="checkbox">
        Child 1<input class="check" name="child" type="checkbox">
        Child 2<input class="check" name="child" type="checkbox">
        Child 3<input class="check" name="child" type="checkbox">
        <br>
        Parent2<input name="parent" class="pc-box" type="checkbox" >
        Child 1 <input class="check" name="child" type="checkbox">
        Child 2 <input class="check" name="child" type="checkbox">
        Child 3 <input class="check" name="child" type="checkbox">

index.js index.js

$(document).ready(function() {

$(".pc-box").click(function() {
if (this.checked) {
       ('.check').prop('checked',$(this).prop('checked'));
    }

 });
   });

here is my fiddle 这是我的小提琴

You can use nextUntil to get the child checkboxes following the parent. 您可以使用nextUntil来获取父级之后的子级复选框。 If you remove the if statement you can also make the parent in to a toggle. 如果删除if语句,还可以使父级进入切换状态。

$('.pc-box').change(function() {
    $(this).nextUntil('.pc-box').prop('checked', $(this).prop('checked')); 
});

Example fiddle 小提琴的例子

You have missed the jquery selector while setting the checkbox value in condition. 在条件中设置复选框值时,您错过了jquery选择器。 also you need to modify the selector to target only the elements before next .pc-box checkbox which acts as parent. 您还需要修改选择器,使其仅定位到下一个.pc-box复选框(充当父级)之前的元素。 Use: 采用:

$(document).ready(function() {
$(".pc-box").click(function() {
 if (this.checked) {
   $(this).nextUntil('.pc-box').prop('checked',$(this).prop('checked'));
 }
});});

Demo 演示版

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM