Reputation: 113
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");
}
});
Upvotes: 1
Views: 1458
Reputation: 388316
Try
$(document).ready(function () {
$('.onoffcheck').change(function () {
$("#node2").toggleClass("panel-off2", this.checked).toggleClass("panel-success", !this.checked);
}).change()
});
Demo: Fiddle
Upvotes: 1
Reputation: 13702
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
});
Upvotes: 1
Reputation: 5444
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");
}
});
});
Upvotes: 1