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 /> <input
type="checkbox" name="cnstates" id="OT" />Ontario<br />
<input type="checkbox" name="cnstates" id="AT" />Alberta
<br /> <input type="checkbox" value="" name="country"
class="childCheckBox" /> United States<br /> <input
type="checkbox" name="usstates" id="NY" />New York<br />
<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 /> <input
type="checkbox" name="instates" id="MU" />Mumbai<br />
<input type="checkbox" name="instates" id="DL" />Delhi
<br /> <input type="checkbox" value="" name="country"
class="childCheckBox" /> Russia<br /> <input
type="checkbox" name="rustates" id="MW" />Moscow<br />
<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);
}
}
);
}
);