Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: if checkbox is checked, toggleClass

Tags:

html

jquery

css

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

like image 667
Kyle Avatar asked Dec 01 '22 09:12

Kyle


2 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), 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.

like image 159
Nick Craver Avatar answered Dec 05 '22 16:12

Nick Craver


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/

like image 23
karim79 Avatar answered Dec 05 '22 16:12

karim79