Reputation: 1047
I have following requirement :
Display a drop down based on hierarchy (Parent child relationship).
Every node should be check-able (A checkbox in every option)
If we select all child nodes, then parent should be checked automatically or vice a versa.
For example : Inside a drop-down I want something like this :
[Checkbox]Element 1
[Checkbox]Element 1.1
[Checkbox]Element 1.2
[Checkbox]Element 1.2.1
[Checkbox]Element 1.2.2
[Checkbox]Element 2
[Checkbox]Element 2.1
[Checkbox]Element 2.2
[Checkbox]Element 2.2.1
[Checkbox]Element 2.2.2
Kindly suggest any solution or if there is any plugin available. The hierarchy may be even more that 4-5 levels in future.
Thanks in advance.
Upvotes: 0
Views: 6196
Reputation: 330
I made dummy code. Hope it will help you.
Html -
<div class="parent">
<input type="checkbox">1
<div>
<input type="checkbox">1.1
<input type="checkbox">1.2
<div>
<input type="checkbox">1.2.1
<div>
<input type="checkbox">1.2.1.1
<input type="checkbox">1.2.1.2
<input type="checkbox">1.2.1.3
</div>
<input type="checkbox">1.2.2
</div>
</div>
<input type="checkbox">2
<div>
<input type="checkbox">2.1
<input type="checkbox">2.2
</div>
</div>
Jquery -
$('input').change(function(){
var status = false;
$(this).next().find('input').prop('checked', this.checked);
status = ($(this).parent().find('> input').not(':checked').length === 0);
$(this).parent().prev().prop('checked', status);
if(status){
$(this).parent().prev().trigger("change");
}
else{
$(this).parents().prev().prop('checked', false);
}
});
You can refer demo - https://jsfiddle.net/dhananjaymane11/w0trj615/1/
Upvotes: 3
Reputation: 1021
You can try this plugin Bootstrap Treeview
I use it for similar cases like yours.
Upvotes: 0