Evonet
Evonet

Reputation: 3640

Javascript for nested 'Select all' checkboxes

I'm trying to display a list of checkboxes with a 'Select All' option for every item, and a 'Select All' item for each group.

I have the following markup:

    <fieldset>
        <label>
            <input type="checkbox" class="checkall"><strong> All</strong>
        </label>
        <fieldset>
            <label>
                <input type="checkbox" name="checkedLocations" class="chkChild checkall" value="China" />
                <strong>&nbsp;&nbsp;China</strong>
            </label>
            <label>
                <input type="checkbox" name="checkedLocations" class="chkChild" value="Hong Kong" checked="checked" />
                &nbsp;&nbsp;&nbsp;Hong Kong
            </label>
        </fieldset>
        <fieldset>
            <label>
                <input type="checkbox" name="checkedLocations" class="chkChild checkall" value="Australia" />
                <strong>&nbsp;&nbsp;Australia</strong>
            </label>
            <label>
                <input type="checkbox" name="checkedLocations" class="chkChild" value="NSW" />
                &nbsp;&nbsp;&nbsp;NSW
            </label>

            <label>
                <input type="checkbox" name="checkedLocations" class="chkChild" value="VIC" />
                &nbsp;&nbsp;&nbsp;VIC
            </label>
        </fieldset>
    </fieldset>

which produces the following checkboxes:

All, China, Hong Kong, Australia, NSW, VIC

What I'm trying to do is to have a Select All checkbox that selects/deselects everything, and a checkbox next to each country (Australia and China in this example) that selects/deselects all the locations in that country.

I'm using the following code:

    $(function () {
        $('.checkall').on('click', function () {
            $(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
        });
        $('.chkChild').on('click', function () {
            $(this).closest('fieldset').find('.checkall').prop('checked', false);
        });
    });

And the 'Select All' works, however when I click on China or Australia, the checkbox doesn't work and the child items aren't selected/deselected.

Upvotes: 0

Views: 1288

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

Because you have both classes on that element

$(function () {
    $('.checkall').on('click', function () {
        $(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
    });
    $('.chkChild').on('click', function () {
        if (!$(this).is('.checkall')) {
            $(this).closest('fieldset').find('.checkall').prop('checked', false);
        }
    });
});

Demo: Fiddle

Upvotes: 1

Related Questions