JQuery: if checked, toggleClass

I am jQuery noob and it seems that I will always be trying to get this simple job to work.

What I want when the checkbox is checked, hide the div with display: none; .

Here's jFiddle an example of what I'm doing a mess.

Thanks for any help or other solutions :)

+4
source share
3 answers

I agree with karim, if you just need to hide / show, use .toggle(bool) , if your example is simplified and you need a class, use .toggleClass("class", bool) , for example:

 $(function(){ $("#checkbox4").change(function() { $("#checkout-shipping-address").toggleClass("show-hide", this.checked) }).change(); });​ 

Here you can check it , the last .change() , to make a state match when the page first loads, this is what I mean .

+11
source

No show-hide class needed. Just pass in the boolean value for the switch and set the initial state of the div using triggerHandler , which allows you to start the event handler associated with the element, which does not actually affect the state of the element:

 $(document).ready(function() { $("#checkbox4").click(function() { $("#checkout-shipping-address").toggle(this.checked); }).triggerHandler('click'); }); 

Demo: http://jsfiddle.net/nQnDG/3/

+6
source

Try using the following code:

 $(function(){ $('#checkbox4').change(function() { $("#checkout-shipping-address").toggleClass("show-hide"); }); }); 

To respond, you need to bind a change or click event.

0
source

All Articles