Toggle class with jquery if the checkbox is checked

I am trying to achieve a simple task using jQuery. I have a checkbox inside a box, and I want to toggle a class on the box with a transition when the checkbox is checked. However, my code is not working as expected. Here is what I have:

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

Check out the JSFIDDLE example here.

Answer №1

Give it a shot

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

Demonstration: See it in action

Answer №2

To start, ensure that the jQuery library is included in your project. Next, it is important to set up an event listener for when the checkbox is changed. Without this, the conditional check will only be executed when the document is ready.

For example:

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

Check out the DEMO here!

Answer №3

To ensure that the toggle functionality activates whenever the checked status changes, it is necessary to include a `change` listener. For a demonstration of this in action, refer to this live example.

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

$(document).ready(function () {
    toggleSwitch(); // initial run
    $('.onoffcheck').on('change', toggleSwitch); // run on every change event
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How can you reference the immediate selector object using jQuery?

I'm currently delving into the realm of jQuery and decided to create a test page equipped with the following code: <a id='encode' href='javascript: void(0)'>encode</a> | <a id='decode' href='javascr ...

Creating unique styles with styled components without the use of selectors

Is it possible to achieve contextual styling without using CSS selectors? For example: <Button primary> <Text>BUTTON</Text> // if the button is primary then have 20px padding else 0 <Icon/> // if the button is primary then ...

What is the best way to incorporate an AppBar featuring a Back to Top button from Material UI for React into my application?

While exploring the Material UI documentation, I came across this interesting code snippet: import React from 'react'; import PropTypes from 'prop-types'; import AppBar from '@material-ui/core/AppBar'; import Toolbar from &ap ...

Interactive element for initiating a HTTP request to NodeJS/Express server to trigger a specific function

I currently have a frontend button implemented using nodejs and express for my server-side backend. The button is supposed to trigger a function that controls the Philips Hue API on the backend via an HTTP request. I have experimented with various approac ...

Modifying the file name during the download process using AngularJS

Looking for a solution to download a file from an ajax GET request in angularjs? Currently, I am using an invisible iframe to trigger the "Save as" popup for the downloaded file. However, I need to change the name of the file before the popup appears. If ...

Having issues with the addClass() method in JavaScript not functioning properly on hover

Coding Challenge <ul class="navBarExtended"> <li><a href="#">Link</a></li> </ul> Styling Solution .onHover{ text-decoration: underline; } Interactive Scripting $("ul.navBarExtended li a").hover( function() ...

React Typescript: exploring the power of dynamic types

Can dynamic typing be implemented? The JSON structure I am working with looks like this: { "fieldName": "Some text", "type": String, "inputType": "text" }, { "fieldName": "Some bool&q ...

Display the item with jQuery once the CSS generated by jQuery has finished loading

Is it possible to delay the visibility of an object until my script finishes loading? I tried using ajaxcomplete() and ajaxSuccess() without success. Check out the code snippet below for an example. There's an image with the id: imagefocus. Whenever ...

Angry Librarians Uncover Secret to Incrementing Variable in Angular.js

Check out my HTML snippet: <div ng-app='app'> <div ng-controller="MyController" ng-init="myVar=7"> {{myVar}} <span ng-init="myVar=myVar+5">{{myVar}},</span> <span ng-init="myVar=myVar+15">{{myVar}},</ ...

Encountering a problem while retrieving JSON or XML data from a URL using jQuery AJAX

Here is a snippet of code that I've been working on: jQuery(document).ready(function(){ var user_key = "asdflk134"; var app_key = "pigasdb95r91bva"; var params = "app_key="+app_key+"&user_key="+user_key+"&format=xml"; jQuery ...

What is the best way to set tab spacing within a textarea using ReactJS and Bootstrap?

One of my goals is to adjust the indentation within the text area by a specific amount when the Tab button is clicked. I am utilizing React JS and Bootstrap. Within the render function, I have set up a bootstrap text area as shown below: <textarea cl ...

I encountered an issue where I am unable to subtract from jQuery's .outerHeight() within an if statement

I've been working on creating an ajax request that triggers when a div is scrolled to the bottom. I thought I had it figured out with this code, but I've run into an issue. Everything works fine without subtracting 100 from the elem.outerHeight() ...

Unable to reach the object property while using the $.each method

Upon receiving an object from an ajax request, I am using $.each to iterate through all the appointments in the object. However, I am encountering an issue where the object appears to be undefined within the $.each loop. Here is the code snippet for my req ...

Personalized cursor image using jQuery.css()

I have designed a .png image that I want to use as a custom cursor for a particular element with the class "next". Here is the code I am using, but it doesn't seem to be working. Is there anything important that I may have overlooked? $('.next& ...

What is the best way to link an Ajax error response to the initial request?

When utilizing the jQuery ajax function to send data to the server in small segments, each piece of data consists of a simple key-value map within the data property given to the ajax function. If a request fails, how can my error event handler pinpoint wh ...

Launch the Image-Infused Modal

I am completely new to the world of Ionic development. Currently, I am working on a simple Ionic application that comprises a list of users with their respective usernames and images stored in an array. Typescript: users = [ { "name": "First ...

Stop the span within the paragraph from breaking onto a new line

I have a situation where I need quote symbols to be placed inside span elements that are children of a p element. Each quote symbol requires slightly different CSS styles, and they must be included in the HTML rather than in the CSS due to backend restrict ...

Avoid form submission when the 'enter' key is pressed in Edge, but not in Chrome or Firefox

I'm dealing with an issue in HTML where a 'details' tag is set to open and close when the user presses enter. However, on Edge browser, pressing enter on the 'details' tag actually submits the form. I've been tasked with preve ...

Angular JS is encountering an issue where the promise object is failing to render correctly

I'm currently learning Angular and I have a question about fetching custom errors from a promise object in Angular JS. I can't seem to display the custom error message on my HTML page. What am I missing? Below is my HTML file - <!DOCTYPE htm ...

The attribute 'inventory' cannot be found in the declaration of 'WarehouseModule'

I am facing an issue with my AngularFire setup. I have recently installed the latest version of AngularFire using npm i @angular/fire and have successfully configured Firestore. However, when attempting to load data into my Firestore database, I encounte ...