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><input type="checkbox" /></div>

* CSS *

div.showIt {
div.hideIt {

* JavaScript (it does not work) *

<script> = true; // needed for ajax to work in certain older browsers and versions


    $(this).change(function(e) {

        $(this).parent().toggleClass('showIt hideIt');

        $(this).closest("div").toggleClass('showIt hideIt');


}); // end .ready()

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
    //               ^ Here provide show those classes which you want to toggle, giving multiple class does not toggle between them

    //This is does same thing as above statement


You do not neeed

div.showIt {

Only toggle the .hideIt It is more than enough


Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+


Please fill the form - I will response as fast as I can!