5

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 :)

3 Answers 3

16

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.

Sign up to request clarification or add additional context in comments.

16 Comments

Wow, thanks! Great explanation and thanks for example as well. The change call is exactly what I was after. :)
I was under the impression that IE does not handle change on checkboxes, and it does not necessarily get fired when using the spacebar to check/uncheck in some browsers. I would instead use click and set the initial state with triggerHandler('click') instead. Please see my answer.
@karim79 - That's the first I heard about IE and change...it had issues with bubbling a change event prior to 1.4.2 (causing .live() issues), but nothing on the actual checkbox that I've seen or heard of. My demo above works in IE8/7 without any issue...I don't have 6 handy to test, but I don't see how it'd fail, onchange is at a pretty basic level in the API :)
I think it's a pre-jQuery 1.4 thing: "As of jQuery 1.4 the change event now bubbles, and works identically to all other browsers, in Internet Explorer."
Unfortunately, I just added this to my live site ands tested it in IE8 (We don't offer IE6 or 7 versions anymore) and it didn't change the state. Karim's answer works, but the checkbox is loaded checked, so it handles the effect in reverse.
|
6

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/

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.