March 12, 2012
How to use jQuery to hide a parent <div>
Question by H. Ferrence
I want to be able to hide an entire container when I check a checkbox.
* HTML *
<div class="showIt">
<div>abc</div>
<div>123</div>
<div><input type="checkbox" /></div>
</div>
* CSS *
div.showIt {
display:inherit;
}
div.hideIt {
display:none;
}
* JavaScript (it does not work) *
<script>
jQuery.support.cors = true; // needed for ajax to work in certain older browsers and versions
$(document).ready(function(){
$(this).change(function(e) {
$(this).parent().toggleClass('showIt hideIt');
$(this).closest("div").toggleClass('showIt hideIt');
});
}); // end .ready()
</script>
Answer by Starx
You are syntactically wrong.
$(this)
on your code does not select any element at that time.
$("input:checkbox").change(function(e) {
// ^ This here tell to select an input element of type `checkbox` and then attach an event to it
$(this).parent().toggleClass('hideIt');
// ^ Here provide show those classes which you want to toggle, giving multiple class does not toggle between them
$(this).closest("div").toggleClass('hideIt');
//This is does same thing as above statement
});
You do not neeed
div.showIt {
display:inherit;
}
Only toggle the .hideIt
It is more than enough