Ways to update row background color based on specific column values

I need to customize the background color of my table rows based on the value in the "Category" column. For example:

Name     Category     Subcategory
A        Paid         B 
C        Received     D

If the Category value is 'Paid', I want the row background to be red, and if it's 'Received', I want it to be green. This functionality needs to be implemented using JavaScript because I am fetching the table rows via Ajax like this:

var table = $('#data').DataTable( {
        
        processing: true,
        serverSide: true,
        bFilter : false,
        ajax: {
            url : "{{ url('reports/gettransactions')}}",
            data: function (d) {
                d.type      = '1';
                d.category = $('select[name=category]').val();
                d.names = $('input[name=name]').val();
                //d.category = 'Salary';
                d.subcategory = $('select[name=subcategory]').val();
                d.fromdate = $('input[name=fromdate]').val();
                d.todate = $('input[name=todate]').val();
            },
        },
        "language": {
        "decimal":        "",
            "emptyTable":     "<?php echo trans('lang.demptyTable');?>",
            "info":           "<?php echo trans('lang.dshowing');?> _START_ <?php echo trans('lang.dto');?> _END_ <?php echo trans('lang.dof');?> _TOTAL_ <?php echo trans('lang.dentries');?>",
            "infoEmpty":      "<?php echo trans('lang.dinfoEmpty');?>",
            "infoFiltered":   "(<?php echo trans('lang.dfilter');?> _MAX_ <?php echo trans('lang.total');?> <?php echo trans('lang.dentries');?>)",
            "infoPostFix":    "",
            "thousands":      ",",
            "lengthMenu":     "<?php echo trans('lang.dshow');?> _MENU_ <?php echo trans('lang.dentries');?>",
            "loadingRecords": "<?php echo trans('lang.dloadingRecords');?>",
            "processing":     "<?php echo trans('lang.dprocessing');?>",
            "search":         "<?php echo trans('lang.dsearch');?>",
            "zeroRecords":    "<?php echo trans('lang.dzeroRecords');?>",
            "paginate": {
                "first":      "<?php echo trans('lang.dfirst');?>",
                "last":       "<?php echo trans('lang.dlast');?>",
                "next":       "<?php echo trans('lang.dnext');?>",
                "previous":   "<?php echo trans('lang.dprevious');?>"
            }
        },
        columns: [
            { data: 'name', name:'name'},
            { data: 'category', name:'category'},
            { data: 'subcategory', name:'subcategory'},
            { data: 'account', name:'account'},             
            { data: 'amount', name:'amount'},       
            { data: 'transactiondate', name:'transactiondate'}
        ],
        dom: 'Bfrtip',

        buttons: [
            {
                extend: 'copy',
                text:   'Copy <i class="fa fa-files-o"></i>',
                title: '<?php echo trans('lang.income_reports');?>',
                className: 'btn btn-sm btn-fill btn-info ',
                exportOptions: {
                    columns: [ 0, 1, 2, 3, 4, 5]
                }
            }, 
            {
                extend:'csv',
                text:   'CSV <i class="fa fa-file-excel-o"></i>',
                title: '<?php echo trans('lang.income_reports');?>',
                className: 'btn btn-sm btn-fill btn-info ',
                exportOptions: {
                    columns: [ 0, 1, 2, 3, 4, 5 ]
                }
            },
            {
                extend:'pdf',
                text:   'PDF <i class="fa fa-file-pdf-o"></i>',
                title: '<?php echo trans('lang.income_reports');?>',
                className: 'btn btn-sm btn-fill btn-info ',
                orientation:'landscape',
                exportOptions: {
                    columns: [0, 1, 2, 3, 4, 5]
                },
                customize : function(doc){
                    doc.styles.tableHeader.alignment = 'left';
                    doc.content[1].table.widths = Array(doc.content[1].table.body[0].length + 1).join('*').split('');
                }
            },
            {
                extend:'print',
                title: '<?php echo trans('lang.income_reports');?>',
                text:   'Print <i class="fa fa-print"></i>',
                className: 'btn btn-sm btn-fill btn-info ',
                exportOptions: {
                    columns: [ 0, 1, 2, 3, 4, 5 ]
                }
            }
        ]
} );

Answer №1

Take a look at the code snippet below along with the descriptions provided in the comments.

This method presents one approach to solving your problem.

var rows = document.getElementsByTagName("TR");  <!-- Selecting the rows -->

for(i = 1; i < rows.length; i++){ 
  let cells = rows[i].getElementsByTagName("TD");
  if (cells[1].innerText === 'Paid') {   <!-- Selecting rows with column value "paid" -->
    rows[i].style.backgroundColor = "red";  <!-- Setting row color to red for indication -->
  }
}
<table id="theTable">   <!-- Assuming this is your table -->
  <tr>
    <th>Name</th>
    <th>Category</th>
    <th>Sub Category</th>
  </tr>
  <tr>
    <td>A</td>
    <td>Paid</td>
    <td>G</td>
  </tr>
  <tr>
    <td>B</td>
    <td>Received</td>
    <td>M</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

"Implemented a user-friendly header and footer that stick to the top and

My goal is to create a fixed header and footer, allowing the main content to scroll underneath while keeping the right navigation in place. To achieve this effect, I've been experimenting with different solutions. One of my attempts can be viewed her ...

An issue arises with React hooks: useMemo and useEffect display a Missing dependency error when attempting to invoke a function

triggerData function is being utilized in multiple functions. However, if I place the function inside the useEffect to prevent missing dependencies, then I am unable to call the triggerData outside of the useEffect i.e., in buildData. How can I resolve the ...

Looking for an alternative to document.querySelectorAll?

My issue involves using querySelectorAll('a') to select all buttons, but I only want to target two specific buttons labeled 'Know More'. How can I achieve this? Below is the code snippet in question: const buttons = document.query ...

Searching for a specific match in JSON data using React streaming technology: encountering issues with the .find method as

Having experience with functional programming in Java, I recently ventured into JavaScript. My current task involves streaming through a JSON output structured like this: { "originatingRequest": { "clientId": 1, "simulationName": "Sea ...

Only JSON objects with a boolean value of true will be returned

I am working on returning JSON objects in JavaScript/TypeScript that have a true boolean value for the "team" property. For example, the JSON data I am using is as follows: { "state": "Texas", "stateId": 1, "team": true }, { "state": "Cali ...

What is the best way to shift <p> slightly to the left using css?

I've created an HTML file structured like this. <html> <head> </head> <body> <div class="final_time"> <p class="final_time_text">some text here</p> </div> </b ...

Stop modal from closing in the presence of an error

My approach involves using a generic method where, upon adding a food item, a modal window with a form opens for the user to input their details. However, since backend validation for duplicate items can only be retrieved after the API call completes. I w ...

Utilizing a jQuery click event to modify the placement of a table

I have a request regarding the tables within the #middlebox. I would like to be able to rearrange the table positions by clicking on the list items. For instance, if the current order of the tables is starter -> soup -> seafood, clicking on the #seaf ...

Determine the Ratio by comparing shared keys within an array of dictionaries

Looking to create a function that can calculate ratios based on specific keys and control which keys are eligible for ratio calculation. num = [{"HCOName":8919,"timestamp":"2019-01-01T00:00:00.000Z","Territory":"USA"}, {"HCOName":8275,"timestamp":" ...

Ensure the accuracy of submitted form information

I am seeking to enhance the validation process for my form, which is already using jquery.validate.min.js for validation. I want to incorporate another layer of validation by making an ajax call to my MySQL database to check if the email address provided i ...

Error Encountered: "JSON Post Failure in ASP.net MVC resulting in 500

Whenever I attempt to send a variable to JSON on ASP.net MVC, I encounter the following error: jquery-2.2.3.min.js:4 GET http://localhost:58525/Order/GetAddress/?userid=42&email=asandtsale%40gmail.com 500 (Internal Server Error) This is my controller ...

How can I delete a hyperlink on a number from my iPhone or iPad?

Is there a way to prevent certain sets of numbers from being linked, like phone numbers do on iPhones? <h2>Table</h2> <table class="table table-sm table-striped table-hover"> <caption class="sr-only">Search Results</caption> ...

Enhancing React components with Hooks and markers

I'm facing a syntax uncertainty regarding how to update React state using hooks in two specific scenarios. 1) I have a state named company and a form that populates it. In the contacts section, there are two fields for the company employee (name and ...

Guide to retriecing a state in Next.js 14

Check out my code below: "useState" // firebase.js import firebase from "firebase/app"; import "firebase/auth"; // Import the authentication module export default async function handler(req, res) { if (req.method !== " ...

The jQuery function is not functioning correctly

Currently, I am in the process of setting up an accordion menu using jQuery and CSS3. Everything is working perfectly fine so far except that the menu always opens upon page load and the code to hide it is not functioning as intended. Here's the link ...

Learn the process of integrating VueJS with RequireJS

I am attempting to set up VueJS with RequireJS. Currently, I am using the following VueJS library: . Below is my configuration file for require: require.config({ baseUrl : "js", paths : { jquery : "libs/jquery-3.2.1.min", fullcalendar : "libs/ful ...

Error: Trying to access the 'map' property of a null value, Using ReactJS with Axios

I'm currently developing a search bar feature where the user can input their query, hit the search button, and the request is stored in search. This request is then sent via Axios and the results are displayed at the end. Everything seems to be workin ...

How to use CSS and Jquery to show a child element right after its parent element

I'm attempting to develop tabbed navigation using my current HTML structure. My goal is to display book titles as tabs and book details BELOW the tabs. Check out this example: or view this: http://jsfiddle.net/syahrasi/Us8uc/ I cannot change the HTM ...

What is the best way to use margin-top and margin-bottom in CSS?

Looking to perfectly center this modal in the middle of the screen with some margin all around. However, struggling to apply margin specifically to the top and bottom! export function Modal() { return ( <div className="fixed inset-0 z-[60] ...

ran into the error that this state is not a function

Every time I run my code, I encounter the error message this.setState is not a function. Can anyone offer guidance on how to fix this issue? Thank you! spiele.listUsers(params, function(err, data) { if (err) console.log(err, err.stack); else con ...