user3201640
user3201640

Reputation: 571

Check the child checkboxes onclick of parent checkbox

I have an html code where there are two parent checkboxes and their children respectively. 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

        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

$(document).ready(function() {

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

 });
   });

here is my fiddle

Upvotes: 1

Views: 3276

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337560

You can use nextUntil to get the child checkboxes following the parent. If you remove the if statement you can also make the parent in to a toggle.

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

Example fiddle

Upvotes: 3

Milind Anantwar
Milind Anantwar

Reputation: 82231

You have missed the jquery selector while setting the checkbox value in condition. also you need to modify the selector to target only the elements before next .pc-box checkbox which acts as parent. Use:

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

Demo

Upvotes: 2

Related Questions