Using CSS, you can select child elements and adjacent elements, so what you are trying to do will work if div
is placed right after the checkbox but if you want to make it work when div
is somewhere else(above the checkbox), you need to use JavaScript, if it's after, you can use +
to select adjacent element or nested adjacent element
Demo
<input type="checkbox" />
<div>Toggle Using CSS</div>
input[type=checkbox]:checked + div {
display: block;
}
div {
display: none;
}
Targetting div
which is farther away somewhere (But not before the checkbox
) like this
Demo 2
input[type=checkbox]:checked + a + .blah .target {
display: block;
}
.target {
display: none;
}
<input type="checkbox" />
<a href="#">Dummy Link</a>
<div class="blah">
<div class="target">Complicated Selector, Isn't It?</div>
</div>
Explanation : input[type=checkbox]:checked + a + .blah .target
Over
here we select the checkbox which is in a checked state, and than we
chain this by selecting the adjacent element which is an anchor tag,
and than we select another adjacent element which is adjacent to a
tag which is div
with a class .blah
, and than we select nested child element with a class .target
Using jQuery To Do (Doesn't matter where the target element is) Demo 3
<input type="checkbox" id="checkme" />
<a href="#">Dummy Link</a>
<div id="show_on_check" style="display:none">
This content should appear when the checkbox is checked
</div>
$(document).ready(function() {
$('#checkme').change(function() {
$('#show_on_check').toggle();
});
});