Change the background color of a checkbox with jQuery by toggling it

I'm currently utilizing the Bootstrap Tree to generate a nested checkbox list (). However, I am looking to enhance the user experience by highlighting the checked items, and ensuring that when a parent is selected, its children are also highlighted. While I've made some progress with this functionality, I've encountered an issue where the background-color of individual child items won't toggle correctly when unchecked. It seems to only work when the parent item is not selected.

$(function checkbox() {
    $("input[type='checkbox']").change(function () {
        $(this).siblings('ul')
            .find("input[type='checkbox']")
            .prop('checked', this.checked);

        $(this).parent('li').toggleClass("highlight");

    });
});

Answer №1

Your code has been modified and can be viewed in a new fiddle: https://jsfiddle.net/pjrzbbea/.

A separate highlight class has been added for the child elements, with a background color that overlaps the parent's background color. The JavaScript now removes the highlight class from child elements when the parent element is highlighted, ensuring correct resetting of children.

$(function checkbox() {
    $("input[type='checkbox']").change(function () {
        var highlightChildClass = 'highlightChild';

        $(this).siblings('ul')
            .find('li')
            .removeClass(highlightChildClass)
            .find("input[type='checkbox']")
            .prop('checked', this.checked);

        var highlightClass = 'highlight';

        if ($(this).closest('ul[role="group"]').length > 0) {
            highlightClass = highlightChildClass;
        } 

        $(this).parent('li').toggleClass(highlightClass);
    });
});

Answer №2

If you have multiple sources that can change the background, toggling the class may not work as expected. It's important to clean up the children when changing the parent element. Below is a modified version of the sample code provided. https://jsfiddle.net/wgpahro4/

$(function checkbox() {
    $("input[type='checkbox']").change(function () {
    $(this).siblings('ul')
        .find("input[type='checkbox']")
        .prop('checked', this.checked);

    //ADDED CODE STARTS HERE!!!!!!!!!!!
    //Clean up children
    if($(this).parent().hasClass("parent_li")){
        if(!this.checked){
           $(this).siblings("ul").find("li").removeClass("highlight");
        }
    }
    //ADDED CODE ENDS HERE!!!!!  

    $(this).parent('li').toggleClass("highlight");

    });
});

Answer №3

To achieve the desired behavior of having each child checkbox highlight while still allowing the parent checkbox to override, you can use a code snippet like the following:

$(function checkHighlight() {
    $("input[type='checkbox']").change(function () {

        if ($(this).siblings('ul').length > 0) {
            var children = $(this).siblings('ul').find('input');
            children.prop('checked', this.checked).change();
        }
        else {
            var item = $(this).parent('li');
            this.checked ? item.addClass('highlight') : item.removeClass('highlight');
        }
    });
});

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

The primefaces remoteCommand tag is failing to function properly as it is unable to pass the HTML content of the current page using jQuery to the managed

Utilizing Jquery's .html() method, I am extracting the HTML of my current page in the following manner. <h:outputScript name="js/jquery-1.7.2.js" /> <h:outputScript> function fetchHtml(){ $('#next').click(function(){ ...

Error with the mongo (1.4.4) query

After running the query like this : collection.find({ "position": { $in: [ 1, 2 ] } }).toArray().... The correct result is returned. However, when I try using $and or $or, such as: collection.find({ $or: [ { "position": 1 }, { "position": 2 } ] }).toAr ...

The CSS styles are not being applied to the header and footer sections in the PDF file created with

When I try to add a header and footer template to the PDF generated by puppeteer, I am facing an issue where the CSS I added is not being fully applied. await page.pdf({ path: filePath, format : 'A4', printBackground : true, margin : { t ...

Looking to extract data from an HTML form?

In my HTML form, I am dynamically creating elements and setting their name and value attributes. When I try to access the value using document.formname.nameoftheelement.value, I receive an error stating that the value is undefined. I then attempted to us ...

Tips for preventing curved links in a radial tree diagram created with d3

I am currently utilizing this code to generate a radial tree diagram for my data. However, I am looking to make a modification to eliminate curved links. My preference is for linear connections instead of curved ones as the curved links can make the visual ...

Display the HTML tag inside a cell of a mat-table

I am currently exploring options to display an HTML tag within a cell of a mat-table in Angular. My goal is to show a colored circle next to the cell value. I have searched online for solutions, but haven't found one that works. If anyone has any insi ...

Tips for choosing a sibling element on hover using CSS

I'm having trouble figuring out how to make the rect element change color to purple when the text is highlighted. Right now, only the text color is changing. Is there a way to achieve this using just CSS? The goal is for the rect to turn purple on ho ...

Retrieve dynamic data for Pivot in Devexpress AngularJS

I am currently working on an AngularJS web app where I am implementing a Pivot using devexpress, specifically utilizing the Field Chooser. You can find the example code here: In the provided example, static data is used. However, I need to fetch data dyna ...

Express 4 app.use not functioning properly

My backend setup is fairly straightforward with a few routes. I prefer to keep the route logic separate from the server.js file, but for some reason, when I make a POST request to the route, it returns a 404 error. In the server.js file: // Import necess ...

Combining multiple dictionaries into one single dictionary array using JavaScript

In my JavaScript code, I am working with an array that looks like this: arr = [{"class":"a"},{"sub_class":"b"},{"category":"c"},{"sub_category":"d"}] My goal is to transform t ...

How to resize and center an image within a div element as they both scale proportionally

Can someone help me figure out how to center a resized image within its container, which should also be centered? I've been struggling with this for 7 hours and can't seem to get it right. Any assistance would be greatly appreciated :-) Here is ...

Safari not properly adjusting height of bootstrap cards within column in row

I'm currently working on a bootstrap and angular project. I've noticed that in Safari, the card heights are not behaving as expected compared to other browsers like Firefox, Chrome, and Edge. I have tried setting the height to 100%, but it seems ...

What is required to run npm rebuild node-sass --force following each instance of a `yarn add` command?

As I attempt to set up the isemail npm library, everything appears to be going smoothly. However, when I execute yarn start:dev, which essentially runs "npm run build:dev && ./scripts/gendevconfig.sh && cross-env BABEL_DISABLE_CACHE=1 NODE_ ...

guide on launching react with pure javascript

Is it feasible to operate react "straight out of the box" using only JavaScript? In essence, I am seeking a way to utilize react by simply utilizing notepad to create the page (without needing to install and configure node etc.). More specifically - 1) ...

arranging data in various categories with React.js

Can anyone figure out why this code is struggling to properly sort based on columns? sort(key){ this.setState({ [`toggle-${key}`]: !this.state[`toggle-${key}`], data: sortBy(this.state.data, [key], this.state[`toggle-${key}`]).map(v => ...

QUnit and a troubleshooting JSONP situation

I am currently working on testing my web app's ability to handle failure scenarios and display the corresponding error messages using QUnit. One particular scenario I am focusing on is when my Data Source is unavailable during app initialization, res ...

Encountering a Console warning while working with the Material UI menu. Seeking advice on how to resolve this issue as I am integrating HTML within a text

Caution: PropType validation failed. The prop text provided to LinkMenuItem is invalid as it should be a string, not an object. Please review the render method of Menu. Below is the code snippet: var menuItems = [ // text is not valid text { route: &ap ...

Tips for setting the active tab in AngularJS with validation included

When I created two tabs, I encountered an issue where clicking the submit button would only validate the first tab and not automatically switch to the second tab. How can I solve this problem? Thank you in advance for your help. angular.module('myA ...

I seem to be stuck trying to figure out what's going wrong when receiving JSON data

I have spent hours researching on Stack Exchange and Google to gather different information. Here is what I have in guess.php: PHP header('Content-type: application/json'); get_rating($cleanMovie); json_encode(array($id)); The get_rating funct ...

Encountering the error message "Unable to access /" on the browser when using express router

Just started working with the express Router for the first time. Here is my route.js: var express = require('express'); var router = express.Router(); router.get('/', function(req, res) { res.send('home page'); }); module.e ...