When a jQuery checkbox is checked, the addClass and toggleClass effects are applied to all DIVs, not just the enclosing DIV

I am working with Bootstrap Cards that have checkboxes inside them. When a checkbox is checked, I want to apply 2 specific classes to the Card DIVs:

  1. Change class="card border-secondary" to class="card border-success"
  2. Change class="card-header" to class="card-header text-white bg-success"

The current jQuery code I have in place applies these changes to all the DIVs on the page when a checkbox is checked. However, the toggle functionality for the border class does not work consistently.

I need help refining the jQuery code so that it only applies the changes to the specific div containing the checkbox and ensuring the border class toggle works correctly every time.

$("input[type='checkbox']").change(function() {
  if ($(this).is(":checked")) {
    $("div.card-header").addClass("text-white bg-success");
    $("div.border-secondary").toggleClass("border-success");
  } else {
    $("div.card-header").removeClass("text-white bg-success");
    $("div.border-secondary").toggleClass("border-success");
  }
});
.... CSS styles here ....

Answer №1

To achieve the desired outcome, it is important to provide more specific instructions. For instance, using 'div.card-header' will target all card headers as you are aware. By utilizing 'closest', you can move up the DOM tree, while 'find' allows you to navigate back down and select the appropriate header.

Consider updating the JavaScript code like this:

$("input[type='checkbox']").change(function() {
  if ($(this).is(":checked")) {
    $(this).closest(".card").find(".card-header").addClass("text-white bg-success");
    $(this).closest(".card").toggleClass("border-success");
  } else {
    $(this).closest(".card").find(".card-header").removeClass("text-white bg-success");
    $(this).closest(".card").toggleClass("border-success");
  }
});

Check out a functioning example here: jsFiddle

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

Utilize module.exports to export objects containing callback functions

I am currently diving into the world of writing my own modules for nodejs. My goal is to create various objects that I can use throughout my application. Here is the result I am aiming for: //assuming we have a database: Person_table(ID int A_I, NAME var ...

"Declare the Status, Refresh the Page, and Specify the Web

After refreshing the page, I am facing an issue where the text corresponding to the current URL is not being displayed. My application consists of a Main component that renders a MiniDrawer component containing a NavLink, followed by routing with the Route ...

Does client-side JS/Angular have an HTTP Connection Timeout feature?

I'm currently using Angular's HttpClient to send HTTP requests and I want to set a specific timeout for them. Although I am aware that I can utilize HTTPInterceptors and include a timeout in RxJS operators, these settings apply to the entire req ...

Ways to implement a backup plan when making multiple requests using Axios?

Within my application, a comment has the ability to serve as a parent and have various child comments associated with it. When I initiate the deletion of a parent comment, I verify the existence of any child comments. If children are present, I proceed to ...

How to access the values or text of siblings using JQuery in a dynamically generated element

My goal is to retrieve the .text() of the sibling customerID from the class"db_record_left" when the class="db_record_left" is clicked. The entire class="db_record" is dynamically generated. However, the issue is that console. ...

Utilizing Normal Mapping with ShaderMaterial, TangentSpace, and fromGeometry in Three.js

I've been struggling to understand normal mapping with Three.js. Despite my efforts, I can't seem to get it right. Below is the code I've been working on: Javascript: var bufferGeometry = new THREE.BufferGeometry(); bufferGeometry.fromGeo ...

Retrieve and showcase images in a slideshow format sourced directly from the Server's directory(folder)

In my application, which is built with .NET C#, I have a feature that allows users to upload images. When an image is uploaded, I dynamically create a folder to store it. For example: strFolder = Server.MapPath("./folder/folder_"+folid+"/") This means th ...

HTML TABS: Make the first TAB automatically selected

I've been experimenting with tabbing in HTML using a tutorial I found on W3SCHOOLS. While the source code provided works fine, I'm encountering an issue with automatically selecting the first tab by default. The tutorial doesn't cover this, ...

Tips for Positioning Content in the Center of a Bootstrap Div

I'm struggling to center the jackpot-item-container div within a chart. Can anyone help me figure this out? Check out my code on CodePen. <div id="jackpot-container" class="col-sm-12"> <div id="jackpot-item-container"> <span id= ...

Retrieving the chosen item from an unordered list using jQuery

Hello, I am currently populating a list using the ul-li HTML tags dynamically. My goal is to retrieve the value of the selected li within the corresponding ul. Despite trying various jQuery methods, I keep getting 'undefined'. Here is how I popul ...

struggling to retain data within scope when utilizing localstorage in angular

Currently, I am utilizing the fileReader to read a file, save the image in localStorage, and then display it on the view. In the controller: angular.module('App')controller('publsherProfileEditCtrl', ['$rootScope', '$sc ...

I am struggling with clicking on Bootstrap's pagination using AngularJS

I'm still getting the hang of Angularjs. I managed to set up a pagination system, but for some reason, I can't seem to interact with it when I run my project. Take a look at this screenshot that illustrates my issue: https://drive.google.com/fil ...

Dealing with ReactJs Unhandled Promise Rejection: SyntaxError - Here's the Solution

Struggling to use the Fetch API in ReactJS to retrieve a list of movies. Encountering an issue, can anyone offer assistance? fetch("https://reactnative.dev/movies.json", { mode: "no-cors", // 'cors' by default }) ...

Issue encountered while importing TypeScript files from an external module in a Next.js project

Encountering an issue within my Next.js project with the following project structure: ├── modules/ │ └── auth/ │ ├── index.ts │ ├── page.tsx │ └── package.json └── nextjs-project/ ├─ ...

The property 'caseSensitive' is undefined and cannot be read

After creating a simple code, I am puzzled by an error message that seems to be case sensitive. However, the code appears correct based on my understanding. Here is the code snippet: App.js const express = require('express'); const path = requir ...

An unexpected error happened while pre-rendering the page "/404". Discover more about this issue here: https://nextjs.org/.../.../prerender-error. The error is caused by TypeError: c.props.href.startsWith

An issue arose while pre-rendering the page "/404". For more information, please visit: https://nextjs.org/docs/messages/prerender-error TypeError: c.props.href.startsWith is not a function at E:\proftfolio_initial\node_modules\next&bsol ...

Troubleshooting problem with Shopify mailto tag

I am facing an issue with external links in my Shopify store. My app injects a script to display a bubble with an anchor tag that redirects users to a specified link. However, Shopify is altering the anchor tag to a different link, resulting in a 404 erro ...

Having trouble loading CSS in an express view with a router

I am encountering an issue where I am unable to load my CSS into a view that is being rendered from a Router. The CSS loads perfectly fine for a view rendered from app.js at the root of the project directory. Below is my current directory structure, node_ ...

Struggling to locate the 'babel-runtime/regenerator' module? Consider importing it locally versus from NPM for a seamless integration

I've been encountering issues with my babel configuration while working on an NPM module that utilizes ES6 features like async/await, static class methods, and import/export. Initially, I faced the common error ReferenceError: regeneratorRuntime is n ...

Using a single function to generate multiple instances of a table in JavaScript

My journey to learning javascript led me to create a simple game called circle of crosses. Below is the code I used: (JS) // JavaScript code here (HTML) <!DOCTYPE html> <html> // HTML code here </html> I came across an issue whil ...