Kyle
Kyle

Reputation: 67244

jQuery: if checkbox is checked, toggleClass

I am a jQuery noob and seems I always will be, been trying to get this simple thing to work.

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

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

Thanks for any help, or other solutions :)

Upvotes: 5

Views: 18474

Answers (3)

karim79
karim79

Reputation: 342795

There is no need for a show-hide class. Just pass a boolean to toggle, and set the initial state of the div by using triggerHandler, which lets you fire an event handler bound to an element without actually affecting 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/

Upvotes: 6

Nick Craver
Nick Craver

Reputation: 630637

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), like this:

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

You can test it out here, the last .change() call is to make the state match when the page first loads, here's what I mean.

Upvotes: 16

jwueller
jwueller

Reputation: 30991

Try the following code:

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

You need to bind the change or click event in order to react.

Upvotes: 1

Related Questions