SO - 17548627

by Arun P Johny

HTML

<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>

JavaScript

$('[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);
})