17 35 Votes

jQuery: Show or hide DIV-container depending on checkbox is checked

Tutorial by Stefan Trost | 05/12/2012 at 17:01

In this tutorial I will show you how to achieve that a DIV container is displayed or hidden depending on the state of a checkbox by using HTML, CSS and JavaScript/jQuery. 

First of all, let us have a look at the HTML for our example:

HTML

We have a checkbox and under this checkbox, there is a DIV container. First of all, this DIV container is invisible (display:none), but after selecting the checkbox, the DIV should be displayed.

<label><input type="checkbox" id="cbshow"> Show DIV</label>

<div id="divshow" style="display:none">
   This content should be displayed
</div>

To be able to call our checkbox and the DIV, we have assigned the IDs  "cbshow" and "divshow" to them.

JavaScript/jQuery

Now, we only need the jQuery code:

if ($('#cbshow').is(:checked)) {
   $('#divshow').show();
} else {
   $('#divshow').hide();
}

In the first line, we text, whether our checkbox "cbshow" is checked. If so, "divshow" will be displayed, if not, it will be hide.

Another possibility is using this code instead:

$('#cbshow').click(function(){
   $('#divshow').toggle(this.checked);
});

The first possibility can be better used, if we would like to add other functions depending on the state of the checkbox.

ReplyPositiveNegative

About the Author

Avatar AuthorYou can find Software by Stefan Trost on sttmedia.com. Do you need an individual software solution according to your needs? - sttmedia.com/contact
Show Profile | Message

 

Related Topics

jQuery: Show and hide elements
Tutorial | 0 Comments

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own articles on askingbox.com. How to do.