Customizing row and column font colors based on checkbox selections

Is there a way to easily change the font colors of table rows and columns based on checkboxes? Ideally, I would like to have checkboxes at the top and left side of the table that, when checked, will change the font color of the corresponding row or column. The goal is to assign a single color to the font. Multiple row and column checkboxes can be selected simultaneously without any issues. Thank you for your assistance!

If you need to view the example, here is a jsfiddle link: https://jsfiddle.net/u6xzfnq7/

.tb {
  font-size: 12px;
  border: 1px solid #CCC;
  font-family: Arial, Helvetica, sans-serif;
}

.tb td {
  padding: 4px;
  margin: 3px;
  border: 1px solid #CCC;
}
  

 <table class="tb">
    <tbody>
        <tr>
            <td></td>
            <td>
                <label class="color-switch">
                    <input type="checkbox" id="check1" /> Switch</label>
            </td>

Answer №1

You have the option to implement something similar to this:

//Here is an example of how you can achieve this functionality:
$('.tb input[type="checkbox"]').change(function() {

  //Remove all selected classes
  $('.tb td').removeClass('selected');

  //Add class to selected rows
  //Select all checked checkboxes in the first column
  //Find parent td and select its siblings
  //Add selected class
  $('.tb tr>td:first-child').find('input[type="checkbox"]:checked').each(function() {
    $(this).parent().parent().addClass('selected').siblings().addClass('selected');
  })

  //Add class to selected columns
  //Select all checkboxes in the first row.
  //Loop through, check if checked.
  //If checked, add class to the column
  $('.tb tr:first-child').find('input[type="checkbox"]').each(function(i) {
    if ($(this).is(":checked"))
      $('.tb tr>td:nth-child(' + (i + 2) + ')').addClass('selected');
  })
})
.tb {
  font-size: 12px;
  border: 1px solid #CCC;
  font-family: Arial, Helvetica, sans-serif;
}

.tb td {
  padding: 4px;
  margin: 3px;
  border: 1px solid #CCC;
}

.selected {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tb">
  <tbody>
    <!-- Your table content goes here -->
  </tbody>
</table>

Answer №2

In order to accomplish this task, I plan to execute the following steps:

var color = "red";
$('input[type=checkbox]').click(function(){
  var id = $(this).attr('id');
  var isChecked = $(this).prop('checked');
  var idNum = $(this).attr('id').replace('check','');
  if(idNum > 7){
    if(isChecked)
      $(this).closest('td').siblings().css('color', color);
    else
      $(this).closest('td').siblings().css('color', '');
  }
  else if(idNum < 23){
    $(this).closest('tr').siblings().each(function(i, tr){
      if(isChecked)
        $(this).find('td:eq("'+idNum+'")').css('color', color);
      else
        $(this).find('td:eq("'+idNum+'")').css('color', '');
    }); 
  }
})
.tb {
  font-size: 12px;
  border: 1px solid #CCC;
  font-family: Arial, Helvetica, sans-serif;
}

.tb td {
  padding: 4px;
  margin: 3px;
  border: 1px solid #CCC;
}

.nochange,
tr {
  background-color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tb">
  <tbody>
    (Table structure and checkboxes omitted for brevity)
  </tbody>
</table>

Answer №3

Even though you have already chosen Eddie's answer as the solution, I wanted to provide my own take on it.
In an effort to build upon his response, here is a code snippet that demonstrates how I would approach the task.
I urge you to pay attention to the JavaScript methods utilized in this code snippet, as that is the primary area where I have made modifications from Eddie's implementation. I have included comments within the code to enhance understanding.

Additionally, I injected some humor into the CSS!

// Adding event listener for checkbox changes within the table
$('.tb input[type="checkbox"]').change(function() {

  // Removing the 'selected' class from all 'tr' and 'td' elements
  $('.tb tr, .tb td').removeClass('selected');

  // Applying the 'selected' class only to checked 'tr' (rows)
  // The selection string can be directly placed inside the $() query without using the .find() method 
  $('.tb tr>td:first-child input[type="checkbox"]:checked').each(function() {
    // Utilizing closest() instead of parent().parent() for better clarity and readability
    $(this).closest('tr').addClass('selected');
  })

  // Applying the 'selected' class only to checked 'td' (columns)
  var tds = $('.tb tr:first-child td');
  $('.tb tr:first-child input[type="checkbox"]:checked').closest('td').each(function() {
    // Styling selected 'tds' based on their index (+1 due to zero-based indexing)
    $('.tb tr>td:nth-child(' + (tds.index($(this)) + 1) + ')').addClass('selected');
  })
})
.tb {
  font-size: 12px;
  border: 1px solid #CCC;
  font-family: Arial, Helvetica, sans-serif;
}

.tb td {
  padding: 4px;
  margin: 3px;
  border: 1px solid #CCC;
}

.selected {
  color: red;
}


/* Here's the fun part - styling intersections */

.selected .selected {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="tb">
  <tbody>
    <!-- Table contents go here -->
  </tbody>
</table>

Further information on .closest(): https://api.jquery.com/closest/
More details on .index(): https://api.jquery.com/index/

I trust this explanation proves beneficial to you.

Answer №4

Uncertain if this aligns with your needs. Feel free to explore a live demo.

<table class="tb">
   <tbody>
      <tr>
         <td></td>
         <td>
            <label class="color-switch">
            <input data-col="0" type="checkbox" /> Switch</label>
         </td>
         <td>
            <label class="color-switch">
            <input data-col="1" type="checkbox" /> Switch</label>
         </td>
      </tr>
      <tr>
         <td>
            <label class="color-switch">
            <input type="checkbox" data-row="0" /> Switch</label>
         </td>
         <td data-row="0" data-col="0">Text</td>
         <td data-row="0" data-col="1">Text</td>
      </tr>
      <tr>
         <td>
            <label class="color-switch">
            <input type="checkbox" data-row="1" /> Switch</label>
         </td>
        <td data-row="1" data-col="0">Text</td>
         <td data-row="1" data-col="1">Text</td>
      </tr>

   </tbody>
</table>
<style type="text/css">
   .tb {
       font-size: 12px;
       border: 1px solid #CCC;
       font-family: Arial, Helvetica, sans-serif;
   }
   .tb td {
       padding: 4px;
       margin: 3px;
       border: 1px solid #CCC;
   }
   .nochange,
   tr {
    background-color: white;
   }

   td.row-checked.col-checked{
    color: red;
   }
</style>

<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script type="text/javascript">
    var $inputCheckboxRow = $('input[type="checkbox"][data-row]');
    var $inputCheckboxCol =  $('input[type="checkbox"][data-col]');

    $inputCheckboxRow.on('change', onInputCheckBoxRowChange );
    $inputCheckboxCol.on('change', onInputCheckboxColChange );

    function onInputCheckBoxRowChange(){
        let row = $(this).data('row');
        if($(this).is(':checked')){
            $('td[data-row='+ row +']').addClass('row-checked')
        }else{
            $('td[data-row='+ row +']').removeClass('row-checked')
        }
    }

    function onInputCheckboxColChange(){
        let col = $(this).data('col');
        if($(this).is(':checked')){
            $('td[data-col='+ col +']').addClass('col-checked')
        }else{
            $('td[data-col='+ col +']').removeClass('col-checked')
        }
    }

</script>

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

I'm wondering why my images aren't fading out correctly

Today, I delved into JQuery and JavaScript for the first time. It's possible that I've made a very basic mistake. Essentially, I have a section in the markup, where JavaScript sets the height to match the viewport. Inside this section, there are ...

Nodejs/Express: The view "error" could not be found in the views directory

I recently made the switch from Jade to EJS as my template engine for my Node.js application. However, when I try to run my app.js file with the EJS template, I am encountering a series of error messages that say "Failed to lookup view 'error' in ...

How can I transfer information from jQuery.ajax() to an angular controller?

In my javascript file script.js, I have a jQuery function named getData(a, b): function getData(a, b) { var d = []; while (a <= b) { $.ajax({ url: "someurl", dataType: 'json', success: function (data) { ...

What is the best way to delete multiple highlighted contenteditable elements in HTML?

Is there a way to easily delete multiple HTML elements by selecting them and pressing the Backspace key? This functionality is available in the WordPress block editor as well as Editor.js. Users can highlight several blocks and remove them with a simple ke ...

A step-by-step guide on generating a dynamic JSON file with JavaScript

I am in need of generating a JSON structure that follows this specific format: {"content": { "properties": { "area_id": "20", "origin": "3", "axis": "1", "x_start": "00", "x_end": "99", "y_start": "00", ...

Adjust the border color of Material UI's DatePicker

https://i.sstatic.net/ZvNOA.png Hello everyone, I am currently working with a DatePicker component from Material UI. My main goal is to change the border color of this component. I have attempted various methods such as modifying classes, adjusting the th ...

Avoiding non-router links from remaining active while using routerLinkActive in Angular

One component in the list item of the navigation bar caught my attention: <div [routerLink]="link" routerLinkActive="bg-blue-100" class="flex w-[80%] mx-auto p-3 rounded-md font-bold text-xl justify-between items-center gr ...

Moving HTML elements using Angular

I have a straightforward page set up like this: https://i.sstatic.net/8Iict.png In the setup, there are 3 <button> elements present. I am interested in relocating the Cancel button to the right side of the page, indicated by an arrow in the image. ...

Yet another query about jQuery validation

I need help validating the promoRent field to ensure it contains a number. While this field is not required, if a value is entered, it must be greater than lotRent. Here's the current code snippet: jQuery.validator.addMethod("PRgreaterThanLotRent", ...

Modify element properties with jQuery

I have 4 links on a page, and I am looking to update the 'rel' attribute by extracting information from the 'href' attribute. Due to limitations, directly changing the 'href' attribute is not possible. Therefore, my approach i ...

Using jQuery to insert a div into another div right before the last div

Let's say we have a div like this: <div id='main'> <div id='child'>my static content</div> </div> $('#main').append("<div class='mycontent'>I'm new box by append</div> ...

Troubleshooting issue: Utilizing $(this) with Vue.js in jQuery method is not functioning as

Initially, I understand that combining jQuery with Vue is not advisable. Nevertheless, I am attempting to modify an element after a click event but encountering issues with $(this). methods: { openSMS() { $(this).hide(); // <-- facing difficulty ...

Guide to changing the background colors of multiple elements when hovered over by the mouse?

I want to customize my website's search bar by changing the background color when it is hovered over. Currently, the search bar has two main elements: the text box and the submit button. I have successfully programmed the text box element to change to ...

Exploring the paths of assets within CSS files in Symfony 2

Issue I am facing a dilemma with my CSS file that contains paths for images, fonts, etc. using the CSS syntax url(..). The structure of my paths is as follows: ... +-src/ | +-MyCompany/ | +-MyBundle/ | +-Resources/ | +-assets/ | +-css ...

Personalize the md-tab component in Angular 2

I'm encountering an issue with styling the md-tab component in Angular 2. While I understand that Angular 2 Materials is currently under development, I am wondering if there is a way to customize it, such as removing the bottom-radius. Below is an exa ...

What is the inner workings of stream.Transform in Node.js?

Recently, I stumbled upon a code snippet on a blog showcasing the usage of the stream Transform class to modify data streams and display the altered output. However, there are certain aspects of this code that leave me puzzled. var stream = require(&apos ...

Angular's UI router is directing users to the incorrect URL

Just starting out with Angular 1 and tasked with adding a new feature to an existing webapp. The webapp utilizes jhipster for backend and frontend generation (Angular 1 and uirouter). I attempted to create my own route and state by borrowing from existing ...

Refresh the Google chart in response to a state change in Vuex

Currently, I am working on a reporting page that will display various graphs. Upon entering the page, an API request is made to retrieve all default information. The plan is to enable users to later select filters based on their inputs. For instance: init ...

Maximizing space efficiency in Bootstrap 5

Hello there I have a query; I am currently utilizing Bootstrap 5 for my website, and it's working well. However, I would like Bootstrap to fill the entire page instead of just 80%; (Refer to image) https://i.sstatic.net/Iswmu.jpg <head> ...

What is preventing the hashmap from including duplicate values in its count in JavaScript?

Currently, I am attempting to tally the occurrences of objects in an array. The array in question has the following structure: [{ Title: 'Einstein', Author: 'Walter Isaacson' }, { Title: 'The Elegant Universe', Author: &apo ...