1

I have a box with a checkbox, I want to insert in jQuery if the checkbox is checked toggle the class on the box with a transition, but it fails and below is the code:

$(document).ready(function(){
if ($('.onoffcheck').is(':checked')) {
    $(".panel-success").toggleClass("panel-off2");
  } else {
          $(".panel-off").toggleClass("panel-success");
}
});

JSFIDDLE

1
  • missed to add jQuery lib in fiddle(left topmost in the fiddle).. Also I dont see any event listener.. Commented Apr 10, 2014 at 8:57

3 Answers 3

1

Try

$(document).ready(function () {
    $('.onoffcheck').change(function () {
        $("#node2").toggleClass("panel-off2", this.checked).toggleClass("panel-success", !this.checked);
    }).change()
});

Demo: Fiddle

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

7 Comments

what is the panel-off and panel-off2 classes
In my website (i have it in local) the code that works in jsfiddle doesn't work because my checkbox is hidded and modified with jquery to make this: bootstrap-switch.org How can i do?
@PedroCorcheroMurga try $('.onoffcheck').on('switchChange.bootstrapSwitch', function () {...
Works perfect now!! Only one thing more, how can make a smooth transition with css in the changing class and change the square to be green when checked and grey when not checked glyphicon class glyphicon-stop off (grey) and class glyphicon glyphicon-stop on (green)
@PedroCorcheroMurga which square
|
1

First make sure to include the jQuery library. Then you have to listen to the checkbox change event. Otherwise the conditional check gets only executed on document ready.

E.g.:

$(document).ready(function(){
    $('.onoffcheck').on('change', function(){
        if ($(this).is(':checked')) {
            $(".panel-success").toggleClass("panel-off2");
        } else {
            $(".panel-off").toggleClass("panel-success");
        }
    });
});

DEMO

Comments

1

You have to add a change listener to make the toggle logic execute on every checked change. See working example

var toggle = function () {
    if ($('.onoffcheck').is(':checked')) {
        $(".panel-success").toggleClass("panel-off2");
    } else {
        $(".panel-off").toggleClass("panel-success");
    }
};

$(document).ready(function () {
    toggle();  // initial execution
    $('.onoffcheck').on('change', toggle); // execute it on every change
});

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.