Yabsley Yabsley - 7 months ago 52
Javascript Question

jQuery show child divs when checkboxes are checked

I have a select input which controls the display of different sets of checkboxes using jQuery. I.E. When you select different options it displays different divs containing more inputs.

<select type="select" name="set" id="set" required>
<option value="">Select</option>
<option value="set1">One</option>
<option value="set2">Two</option>
</select>

<div id="set1" class="checkboxes">
<input type="checkbox" name="set1-questions1" id="set1-questions1">
<div id="set1-questions1-qs"></div>
...
</div>
<div id="set2" class="checkboxes">
...
</div>


jQuery

$('#set').change(function(){
$('.checkboxes').hide();
$('#' + $(this).val()).show();
});


This works OK but I'd like the checkboxes within each div to control the display of the sub div. I.E you select an option from the select and then check a checkbox to display the sub div.

DEMO with full markup and the first part working

I don't know how to achieve the second part. Do I need a function to link the checkboxes to the corresponding divs and then show/hide based on if it is checked or not?

Answer

Add a change handler to the checkboxes, and then toggle the corresponding <div> based on the state of the checkbox:

$('div.checkboxes input[type="checkbox"]').on('change', function() {
   $('#' + this.id + '-qs').toggle( this.checked ); 
});

Fiddle