User clicks on a checkbox, shows hidden/nested subcheckboxes
-
06-02-2021 - |
Pergunta
Is there a way to hide/show a sub/child checkbox group depending if a parent checkbox is checked? I was able to do something similar with a drop down: if a user selects an item in a drop down, another group of forms will go from hidden to shown:
<script src="/SiteAssets/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="/siteassets/jsLib/jquery-3.3.1.min.js" type="text/javascript"></script>
<script>
//able to hide the sub categories...
$(document).ready(function() {
$('nobr:contains("subcat - parent a")').closest('tr').hide();
$('nobr:contains("subcat - parent b")').closest('tr').hide();
$('nobr:contains("subcat - parent c")').closest('tr').hide();
$('nobr:contains("subcat - pet dog")').closest('tr').hide();
$('nobr:contains("subcat - pet cat")').closest('tr').hide();
$('nobr:contains("subcat - pet fish")').closest('tr').hide();
//...but want to enable them if the parent is checked: the below not working.
$("input[title='checkbox parent']".checked(function() {
if ($("input[title='checkbox parent']").val()=="Parent #B")
{
$('nobr:contains("subcat - parent a")').closest('tr').hide();
}
else{
$('nobr:contains("subcat - parent b")').closest('tr').show();
}
});
});
</script>
So basically, I'm looking for something like:
Pet Check Box Group
+Dog
+Cat
+Fish
I select the Dog check box it will expand the sub checkbox group:
Pet Check Box Group
-Dog
(Dog Check Box Group)
+German Sheppard
+Golden Retriever
+Beagle
+Cat
+Fish
Also, the grouping of the child is associate it with the parent. Hopefully that makes sense.
Solução
If you have the following scenario:
<input type="checkbox" id="parent1" /> Dog
<div data-parentid="parent1">
<input type="checkbox" id="child1"> German Sheppard
<input type="checkbox" id="child2"> Golden Retriever
<input type="checkbox" id="child3"> Beagle
</div>
you could use the change event to display the corresponding sub-checkboxes:
$('[type="checkbox"]').change(function() {
var shouldBeDisplayed = $(this).prop('checked');
$('div[data-parentid="' + $(this).attr('id') + '"]').toggle(shouldBeDisplayed);
});