JSFiddle - React, Tailwind, and code Playground
HTML
<form>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Parent 1<br />
<input type="checkbox" class="childCheckBox" /> Child 1-1<br />
<input type="checkbox" class="childCheckBox" /> Child 1-2<br />
<input type="checkbox" class="childCheckBox" /> Child 1-3<br />
<input type="checkbox" class="childCheckBox" /> Child 1-4<br />
<input type="checkbox" class="childCheckBox" /> Child 1-5<br />
</fieldset>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Parent 2<br />
<input type="checkbox" class="childCheckBox" /> Child 2-1<br />
<input type="checkbox" class="childCheckBox" /> Child 2-2<br />
<input type="checkbox" class="childCheckBox" /> Child 2-3<br />
<input type="checkbox" class="childCheckBox" /> Child 2-4<br />
<input type="checkbox" class="childCheckBox" /> Child 2-5<br />
</fieldset>
<fieldset>
<input type="checkbox" class="parentCheckBox" /> Parent 3<br />
<input type="checkbox" class="childCheckBox" /> Child 3-1<br />
<input type="checkbox" class="childCheckBox" /> Child 3-2<br />
<input type="checkbox" class="childCheckBox" /> Child 3-3<br />
<input type="checkbox" class="childCheckBox" /> Child 3-4<br />
<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').attr('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);
}
}
);
}
);