JSFiddle - React, Tailwind, and code Playground

by Ali Khaled

HTML

<form>
		<input type="checkbox" class="mainCheckBox" /> Select All <br />
		<fieldset>
			<input type="checkbox" class="parentCheckBox" /> North America <br />
			<div class="content">
				<input type="checkbox" value="" name="country"
					class="childCheckBox" /> Canada<br /> &nbsp; &nbsp;<input
					type="checkbox" name="cnstates" id="OT" />Ontario<br />
				&nbsp; &nbsp;<input type="checkbox" name="cnstates" id="AT" />Alberta
				<br /> <input type="checkbox" value="" name="country"
					class="childCheckBox" /> United States<br /> &nbsp; &nbsp;<input
					type="checkbox" name="usstates" id="NY" />New York<br />
				&nbsp; &nbsp;<input type="checkbox" name="usstates" id="DC" />Washington
				DC
			</div>
		</fieldset>

		<fieldset>
			<input type="checkbox" class="parentCheckBox" /> Asia <br />
			<div class="content">
				<input type="checkbox" value="" name="country"
					class="childCheckBox" /> India<br /> &nbsp; &nbsp;<input
					type="checkbox" name="instates" id="MU" />Mumbai<br />
				&nbsp; &nbsp;<input type="checkbox" name="instates" id="DL" />Delhi
				<br /> <input type="checkbox" value="" name="country"
					class="childCheckBox" /> Russia<br /> &nbsp; &nbsp;<input
					type="checkbox" name="rustates" id="MW" />Moscow<br />
				&nbsp; &nbsp;<input type="checkbox" name="rustates" id="DC" />Aldan
			</div>
		</fieldset>

	</form>

JavaScript

$(document).ready(
    function() {
       $('input.childCheckBox').change(function() {
            $(this).closest('fieldset').find('.parentCheckBox').prop('checked',
                $('input.childCheckBox').length === $('input.childCheckBox:checked').length 
            ); 
        });
        
        //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').attr('checked') == true && this.checked == false)
                    $(this).parents('fieldset:eq(0)').find('.parentCheckBox').attr('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').attr('checked', flag);
                }
            }
        );
    }
    );