简体   繁体   中英

Jquery if checked toggle class

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

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.

Eg:

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

DEMO

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
});

Try

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

Demo: Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM