I have several dynamic checkbox groups (ul>li>checkbox>ul>li>checkbox) and need to change the check state of the parent to unchecked if children are unchecked or to indeterminate if only one child is checked. I have working unchecking the children if the parent is unchecked but need to tie each group together but separate from the other groups. The child is unchecking the top level parent item in the list of groups.
HTML
<div class="form-group">
<ul>
<li ng-repeat="state in filtersController.filtersModel().states">
<input type="checkbox" name="{{state.displayName}}" id="{{state.displayName}}" class="parent" ng-checked="true" ng-model="state.selected" ng-change="filtersController.filterChanged(state)">
<label for="{{state.displayName}}">{{state.displayName}}</label>
<ul>
<li ng-repeat="county in filtersController.filtersModel().counties">
<div ng-show="displayCounties(county, state)">
<input type="checkbox" name="{{county.displayName}}" id="{{county.displayName}}" class="child" ng-checked="true" ng-model="county.selected" ng-change="filtersController.filterChanged(county)">
<label for="{{county.displayName}}">{{county.displayName}}</label>
</div>
</li>
</ul>
</li>
</ul>
</div>
JS
this.getChecked = function () {
$('input[type=checkbox]').change(function () {
// parent unchecked will uncheck children
$(this).parent().find('li input[type=checkbox]').prop('checked', $(this).is(':checked'));
$(this).closest('ul').find('ul li input[type=checkbox][class=parent]').first().prop('indeterminate', $(this).is(':checked'));
});
$('li :checkbox').on('click', function () {
var $chk = $(this),
$li = $chk.closest('li'),
$ul, $parent;
if ($li.has('ul')) {
$li.find(':checkbox').not(this).prop('checked', this.checked);
}
do {
$ul = $li.parent();
$parent = $ul.siblings(':checkbox');
if ($chk.is(':checked')) {
$parent.prop('checked', $ul.has(':checkbox:not(:checked)').length === 0);
} else {
$parent.prop('checked', false);
}
$chk = $parent;
$li = $chk.closest('li');
} while ($ul.is(':not(.someclass)'));
});
};
I am using AngularJS for my data structure and jQuery for to interact with the checkboxes.