JSFiddle - React, Tailwind, and code Playground

by Tushar Gupta

HTML

<form>
    <fieldset>
        <input type="checkbox" class="parentCheckBox" />Parent 1
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 1-1
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 1-2
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 1-3
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 1-4
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 1-5
        <br />
    </fieldset>
    <fieldset>
        <input type="checkbox" class="parentCheckBox" />Parent 2
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 2-1
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 2-2
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 2-3
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 2-4
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 2-5
        <br />
    </fieldset>
    <fieldset>
        <input type="checkbox" class="parentCheckBox" />Parent 3
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 3-1
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 3-2
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 3-3
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 3-4
        <br />&nbsp;&nbsp;&nbsp;&nbsp;
        <input type="checkbox" class="childCheckBox" />Child 3-5
        <br />
    </fieldset>
</form>

JavaScript

$(document).ready(

function () {
    //clicking the parent checkbox should check or uncheck all child checkboxes
    $(".parentCheckBox").click(

    function () {
        $(this).parents('fieldset:eq(0)').find('.childCheckBox').prop('checked', this.checked);
    });
    //clicking the last unchecked or checked checkbox should check or uncheck the parent checkbox
    $('.childCheckBox').click(

    function () {
        if ($(this).parents('fieldset:eq(0)').find('.parentCheckBox').prop('checked') == true && this.checked == false) $(this).parents('fieldset:eq(0)').find('.parentCheckBox').prop('checked', false);
        if (this.checked == true) {
            var flag = true;
            $(this).parents('fieldset:eq(0)').find('.childCheckBox').each(

            function () {
                if (this.checked == false) flag = false;
            });
            $(this).parents('fieldset:eq(0)').find('.parentCheckBox').prop('checked', flag);
        }
    });
});