What is the best way to assign a unique color to two overlapping cells in an HTML table using HTML and jQuery?

I have a task to highlight a row or column when a checkbox is selected, similar to the example shown in the image below.

How can I adjust the code so that the overlapping cell gets a different color instead of green or yellow? For instance, in the image below, "Jackson" should be highlighted with a different color - let's say blue.

https://i.sstatic.net/HDm41.png

Code:

    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script>
        $(document).ready(function () {
            $("input[type='checkbox']").change(function (e) {
                if ($(this).is(":checked")) {
                    $(this).closest('tr').addClass("highlight");
                } else {
                    $(this).closest('tr').removeClass("highlight");
                }


            });
            $('th').click(function () {
                // $(this).addClass('selectedcc');
                var $currentTable = $(this).closest('table');
                var index = $(this).index();
                // $currentTable.find('td').removeClass('selectedcc');
                $currentTable.find('tr').each(function () {
                    $(this).find('td').eq(index).toggleClass('selectedcc');

                });

            });


        });
    </script>

    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
        }
        th, td {
            padding: 5px;
        }

        .highlight td {background: yellow;}

        .selected {
            background-color: yellow;
        }

        .selectedcc {
            background-color: greenyellow;
        }
    </style>

</head>


<body>

    <table style="width:60%" id="dataTable">
        <tr>
            <th><input type="checkbox" name="vehicle" value="Bike">All</th>
            <th><input type="checkbox" name="vehicle" value="Bike">Firstname</th>
            <th><input type="checkbox" name="vehicle" value="Bike">Lastname</th>
            <th><input type="checkbox" name="vehicle" value="Bike">Points</th>
        </tr>
        <tr>
            <td><input type="checkbox" name="vehicle" value="Bike"></td>
            <td>Jill</td>
            <td>Smith</td>
            <td>50</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="vehicle" value="Bike"></td>

            <td>Eve</td>
            <td>Jackson</td>
            <td>94</td>
        </tr>
        <tr>
            <td><input type="checkbox" name="vehicle" value="Bike"></td>

            <td>John</td>
            <td>Doe</td>
            <td>80</td>
        </tr>
    </table>

</body>

Answer №1

If you want the tr to have the class highlight and the td itself to have a class of selectedcc, you can achieve this with a single selector:

.highlight .selectedcc {
    background-color: red;
}

It's also worth noting that you can improve the logic in your jQuery code by combining the two event handlers into one. Here is an example:

$(document).ready(function() {
    $("input[type='checkbox']").change(function(e) {
    var $checkbox = $(this);
       if ($checkbox.parent().is('td')) {
            $checkbox.closest('tr').toggleClass("highlight", this.checked);
        } else {
            var index = $(this).parent('th').index();
            $(this).closest('table').find('tr').each(function() {
                $(this).find('td').eq(index).toggleClass('selectedcc', $checkbox.prop('checked'));
            });
        }
    });
});
table,
th,
td {
    border: 1px solid black;
    border-collapse: collapse;
}

th,
td {
    padding: 5px;
}

.highlight td {
    background: yellow;
}

.selected {
    background-color: yellow;
}

.selectedcc {
    background-color: greenyellow;
}

.highlight .selectedcc {
    background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="width:60%" id="dataTable">
    <tr>
        <th><input type="checkbox" name="vehicle" value="Bike">All</th>
        <th><input type="checkbox" name="vehicle" value="Bike">Firstname</th>
        <th><input type="checkbox" name="vehicle" value="Bike">Lastname</th>
        <th><input type="checkbox" name="vehicle" value="Bike">Points</th>
    </tr>
    <tr>
        <td><input type="checkbox" name="vehicle" value="Bike"></td>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="vehicle" value="Bike"></td>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="vehicle" value="Bike"></td>
        <td>John</td>
        <td>Doe</td>
        <td>80</td>
    </tr>
</table>

Answer №2

It seems that an answer has already been accepted...
Apologies for the slow coding...

Nevertheless, I had a blast tackling this problem, so I've decided to share my solution regardless.

Yes, my code is slightly longer than the existing solution... .oO(...)

However, my approach not only includes a properly functioning "all" checkbox but also accounts for potential additions related to the "data" checkboxes. (Although I must admit, I'm currently clueless about their intended use... For now. lol!)

FIDDLE

$(document).ready(function(){

    $("input[type='checkbox']").change(function() {
        var $currentTable = $(this).closest('table');
        var index = $(this).parent().index();


        if( $(this).hasClass("data") ){ // ---------------------------------------- DATA checkboxes
                                        // --------------------- Does nothing for now...
                                        // --------------------- You may add code here.
            return;                     // --------------------- But keep the return to prevent row toggle.
        }

        if( $(this).hasClass("all") ){  // ---------------------------------------- ALL checkbox
            $("input[type='checkbox']").each(function(){
                if( $(this).hasClass("thCheck") || $(this).hasClass("tdCheck") ){
                    $(this).click();
                }
            });
            $("input[type='checkbox']").hasClass("tdCheck").click();
        }      

        if( $(this).hasClass("thCheck") ){  // ------------------------------------- COLUMN

            $(this).closest('tr').siblings().each(function(){
                // GREEN!
                $(this).children("td").eq(index).toggleClass("selectedColumn");

                // RED!
                if( $(this).children().hasClass("selectedRow") ){
                    $(this).children("td").eq(index).toggleClass("crossing");
                }
            });

        }else{  // ----------------------------------------------------------------- ROW

            // If a row is already selected --> crossing!
            $(this).closest('tr').children("td").each(function () {
                if( $(this).hasClass("selectedColumn") ){
                    $(this).toggleClass("crossing");
                }
            });

            // YELLOW!  
            $(this).closest("tr").children().toggleClass("selectedRow");
            // Except the TD that has the checkbox
            $(this).closest("tr").children().eq(0).toggleClass("selectedRow");

            // RED!
            $(this).children("td").each(function(){
                if( $(this).hasClass("selectedColumn") ){
                    $(this).children("td").addClass("crossing");
                }else{
                    $(this).children("td").remove("crossing");
                }
            });
        }
    });
});

Answer №3

To check whether an element already has the "selected" class, you can utilize the jQuery method .hasClass. If it does have the "selected" class, you can then apply a different class to give it a new color, such as blue. Similarly, when adding the "selected" class, use .hasClass to determine if the element already has the "highlight" class. If it does, go ahead and apply your new blue class.

Remember to remove the blue class if it has been applied when unchecking a checkbox.

Answer №4

For a unique look, consider implementing this approach where cells with both classes are styled differently:

function applyDifferentColorToOverlapCells(){
  // Select all cells that have both classes
   $("#datatable td.selected.selectedcc").removeClass().addClass("overlapcssclass")
}
 $("input[type='checkbox']").change(function (e) {
                if ($(this).is(":checked")) {
                    $(this).closest('tr').addClass("highlight");
                } else {
                    $(this).closest('tr').removeClass("highlight");
                }

              applyDifferentColorToOverlapCells();

            });
            $('th').click(function () {
                var $currentTable = $(this).closest('table');
                var index = $(this).index();
                $currentTable.find('tr').each(function () {
                    $(this).find('td').eq(index).toggleClass('selectedcc');

                });
               applyDifferentColorToOverlapCells();
            });

Answer №5

Here is my proposal:

  • Organize the handlers in rows and columns
  • Apply a new class after toggling if cells that are already selected exist

$(function () {
  // Rows
  $('#dataTable tr:gt(0)').find(':checkbox').change(function (e) {
    var index = 1 + $('#dataTable tr:gt(0)').find(':checkbox').index(this);
    $('#dataTable tr:eq(' +index + ')').find('td').toggleClass('highlight');
    if (this.checked) {
      $('#dataTable tr:eq(' +index + ')').find('td.highlight.selectedcc').removeClass().addClass('overlappedcells');
    } else {
      $('#dataTable tr:eq(' +index + ')').find('td.overlappedcells').removeClass().addClass('selectedcc');
    }
  });
  // Columns
  $('#dataTable tr:eq(0)').find(':checkbox').click(function () {
    var index = $('#dataTable tr:eq(0)').find(':checkbox').index(this);
    $('#dataTable tr').find('td:eq(' + index + ')').toggleClass('selectedcc');
    if (this.checked) {
      $('#dataTable tr').find('td:eq(' + index + ').highlight.selectedcc').removeClass().addClass('overlappedcells');
    } else {
      $('#dataTable tr').find('td:eq(' + index + ').overlappedcells').removeClass().addClass('highlight');
    }
  });
});
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
th, td {
  padding: 5px;
}

.highlight {
  background: yellow;
}

.selectedcc {
  background-color: greenyellow;
}

.overlappedcells {
  background-color: darkslategray;
}
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

<table style="width:60%" id="dataTable">
    <tr>
        <th><input type="checkbox" name="vehicle" value="Bike">All</th>
        <th><input type="checkbox" name="vehicle" value="Bike">Firstname</th>
        <th><input type="checkbox" name="vehicle" value="Bike">Lastname</th>
        <th><input type="checkbox" name="vehicle" value="Bike">Points</th>
    </tr>
    <tr>
        <td><input type="checkbox" name="vehicle" value="Bike"></td>
        <td>Jill</td>
        <td>Smith</td>
        <td>50</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="vehicle" value="Bike"></td>
        <td>Eve</td>
        <td>Jackson</td>
        <td>94</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="vehicle" value="Bike"></td>
        <td>John</td>
        <td>Doe</td>
        <td>80</td>
    </tr>
</table>

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

Adding dynamically fetched JSON to an existing table

http://jsfiddle.net/mplungjan/LPGeV/ What could be improved in my approach to accessing the response data more elegantly? $.post('/echo/json/',{ "json": JSON.stringify({ "rows": [ { "cell1":"row 2 cell 1", "cel ...

Looking to have a countdown begin automatically as soon as the page loads?

Is there a way to create a time counter in jQuery/JS that begins counting when a visitor first enters my website (on page load)? I am looking for a function or similar solution to track the length of time a visitor spends on my website (in seconds) so tha ...

Div scrolling allows for parallel viewing of PDFs in a side by side arrangement

I have two scrollable elements on my webpage: one positioned on the left side and the other on the right side. The left element is a regular div, while the right element is an object containing an embedded PDF. <object width="100%" height=&quo ...

Jquery Ajax Issue: The Page_Load method is running instead of the intended code

I have a method in my code that is supposed to return a csv file when called from the client side, but it currently just returns a simple string. public partial class ResourceEdit_PriceSheet : xCI.Site.Web.BasePage { protected void Page_Load( object s ...

Header media query in CSS3 not functioning as expected

Currently, I have two separate style sheets for mobile and desktop versions. My intention is to default to the mobile style sheet. Upon examining my header, I have included the following: <link rel='stylesheet' media='all' href=&ap ...

Having issues with the functionality of single click in jQuery

I tried to remove the attribute element from a list item, but I am struggling to achieve the desired outcome. When clicking on a list item, it should add a class called "important," otherwise, the class should not exist. Here is my attempt using jQuery: ...

The res.download() function in Express is failing to deliver the accurate URL to the client

When trying to utilize the res.download() method for downloading specific files from a server, there is an issue where triggering the res.download does not redirect the client to the correct URL. The files intended for download are located in a directory s ...

Enhancing AJAX calls in Spine by attaching a data object using $.ajaxSetup()

I have implemented the $.ajaxSetup() function to add extra parameters to all my AJAX requests in Spine. However, it's not working as expected. When I use $ajaxSetup() in this way, GET requests work properly, but the parameters are replaced in POST re ...

Occupying the entire width of a screen

Struggling to tidy up a website I'm working on for a client. I've spent countless hours trying to solve this issue! With my limited knowledge, I could really use some help with the code. The main challenge is making the top section of the site (o ...

Blending PHP with jQuery

I'm currently working on the same page as before but this time, I'm using it to experiment with jQuery. I'm trying to learn it for my 'boss', but unfortunately, I can't seem to get the JavaScript in this file to run at all, le ...

.displaying a grid of div elements is not functioning as expected

On a single page, there is a grid of Divs (2 by 3) with a menu (<li> in <lu>) positioned to the left of the grid. Each menu section contains its own grid of divs, all enclosed within one main div to facilitate manipulation. Menu Sections: < ...

Ensure that the keyboard remains open in an Ionic chat app when a button is clicked

Having some trouble with my Ionic v1 chat application. Everything is set up, but I'm running into an issue where clicking on the send button causes the keyboard to lose focus from the input and then close. I've tried several solutions, but none ...

I'm seeking an easy method to adjust the x and y coordinates of a popup rectangle with a fixed size. Can anyone provide

Is there a way to create a simple pop-up rectangle, possibly using jQuery or a similar tool, that presents a scaled-down canvas view of a larger browser window (1000px x 1600px), allowing users to click and determine the x/y position within the full window ...

Instructions for inserting <tr></tr> after every fourth iteration of <td></td> in the loop

I am trying to create a list of twenty people with each tr containing 4 people, and I want to break from the loop after every fourth number. Each td value should be incremented in order. This is the code snippet I have been working on: <?php for ($i ...

Exploring the capabilities of jQuery in conjunction with HttpHandlers

I'm encountering an issue trying to retrieve HTML from a HttpHandler through jQuery. Below is the jQuery script I am using to call the handler: $.get('http://localhost:56964/LoadComments.axd?storyID=' + storyID ,function(data) { alert(data) ...

Updating the placeholder text of a textarea using a conditional statement in PHP

I currently have a textarea within a form that is being outputted: <textarea id='textarea' name='msg' rows='2' maxlength='255' cols='80' placeholder=' Share a thought...'></textarea> ...

Retrieving data from an Ajax request

I am struggling with extracting the HP and PCP Payment fields from the JSON string obtained through a Jquery Ajax request: function DoPaymentSearch() { var start,end; start=Date.now(); var getQuotesSuccess = function(results){ end=Date.now(); alert(JSON.s ...

The reasons behind the unsightly gaps in my table

Here is the HTML code snippet: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML> <HEAD> <script type='text/javascript' src='js/jquery-1.10.2.min.js'></ ...

Looking to develop a multi-tiered menu component?

I am currently using aurelia along with ES6 to develop a multi-level menu component. The JSON data structure that I'm working with looks like this: data: [ levelId: 1, label: 'Level1', childItems: [ { levelId: 2, labe ...

Efficiently refresh several DIV elements with a single JSON request

After extensive searching, I've come to the conclusion that due to my limited proficiency in javascript, I need some help. The issue at hand is with a json format output produced by an ASP page on a separate webserver, which looks something like this: ...