Group checkboxes in JSFiddle: Part2 [closed]

2019-09-26 10:12发布

Group checkboxes in JSFiddle : Part 1

After solving Part 1 for Global Checkbox for All Check/Uncheck. I have couple other issues to solve.

  1. If I unchecked any of the items from list. Automatically Global (Check all) should be unchecked.

enter image description here

  1. If I checked all of items individually. Automatically Global (Check all) should be checked. like this. enter image description here

Code

 <fieldset>
    <!-- these will be affected by check all -->
    <div><input type="checkbox" ID="checkall1"> Check all</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>
<fieldset>
    <!-- these won't be affected by check all; different field set -->
    <div><input type="checkbox" ID="checkall2"> Check all</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>

JS

   $('[id^=checkall]').click(function(){
    $(this).closest('fieldset').find('input').not(this).prop('checked',this.checked);
});

JSFiddle

1条回答
贼婆χ
2楼-- · 2019-09-26 10:35

Register a callback which will check whether all the checkboxes in the current group is checked or not

$('input[id^=checkall]').click(function(){
    $(this).closest('fieldset').find('input').not(this).prop('checked',this.checked);
});

$(':checkbox').not('[id^=checkall]').click(function(){
    var all = $(this).closest('fieldset').find('[id^=checkall]');
    var chks = $(this).closest('fieldset').find('input').not(all);

    all.prop('checked', chks.length == chks.filter(':checked').length);
})

Demo: Fiddle

查看更多
登录 后发表回答