I have a Parent-Child Hierarchy of checkboxes in my ASP.NET MVC application. I have it working where if you select a parent, the children are all selected. However, I'd like the parent(s) to become indeterminate if you deselect their child.
Jsfiddle: https://jsfiddle.net/vx4zvabg/2/
For instance, if you check Admin, then all checkboxes are selected in the children below. However, I'd like it to make the parent indeterminate if a child is unchecked. Further, make the parent completely unchecked if there are no children checked.
I have found solutions online, however, they have all been overly complicated or don't use actual <input type="checkbox"> for the checkboxes. I figure there must be a simple way to get this handled.
Activity Model:
public class Activity
{
public int ActivityId { get; set; }
public string Name { get; set; }
public bool IsAllowed { get; set; }
public IList<Activity> Children { get; set; } = new List<Activity>();
}
Razor Helper:
@helper CheckBoxShowTree(IEnumerable<Activity> parents)
{
var Html = ((System.Web.Mvc.WebViewPage)WebPageContext.Current.Page).Html;
<ul style="list-style:none;">
@foreach (var child in parents)
{
<li>
@Html.HiddenFor(x => child.ActivityId)
@Html.HiddenFor(x => child.Name)
@Html.CheckBoxFor(x => child.IsAllowed, new { @class = "groupsusers-checkbox", @style = "margin-right:5px; cursor:pointer;", @value = child.ActivityId })
@Html.LabelFor(x => child.IsAllowed, child.Name, new { @class = "build-checkbox-label", @style = "font-weight:normal; margin-top:-2px;" })
@if (child.Children.Any())
{
@CheckBoxShowTree(child.Children)
}
</li>
}
</ul>
}
JQuery:
$(function () {
$("input[type='checkbox']").change(function () {
var val = $(this).val();
$(this).siblings('ul').find("input[type='checkbox']").prop('checked', this.checked);
});
});
The Helper / Model may be irrelevant here. The JS just really needs to be generalized for a checkbox hierarchy and checking all children if parent is selected / indeterminate if some children are selected / unchecking parents if no children selected.
Additionally, the actual value (value="true") ONLY matters for the farthest children on the post for me. The hierarchy is just used in this particular case to make selecting those nodes easier. The value on the checked parent with no children is irrelevant to me.
I appreciate any help. I've been at this for over a day and JS / JQuery is not a strength for me. I have attempted to use Kendo UI and jstree as well, but it doesn't work in my situation. I think it is simpler than what those kits provide.