Applying a color scheme to the Datatable rows based on the filters

I am looking for a way to dynamically highlight specific rows in a table based on data retrieved from the server. For example, if the data contains "Activated", I want to change the background color of that row to green.

Check out this code snippet for more details-

    for(i=1; i<=adminlen;i++)
        {           
            if(adminresults.drivers[i-1].loginstatus !== "blocked") {
                var loginstate = "Block";
            } else {
                var loginstate = "Unblock";
            }                       
            if(admins[i-1].driver_status === 'ON - FREE') {
                var linkone = '</td><td><a href="#" class="btn btn-success 
                btn-xs"><i class="fa fa-taxi"></i>'+admins[i-
                 1].driver_status;
             } else if(admins[i-1].driver_status === 'ON - TRIP') {
                 var linkone = '</td><td><a href="#" class="btn btn-default 
                   btn-xs"><i class="fa fa-taxi"></i>'+admins[i-
                   1].driver_status;
             } else if(admins[i-1].driver_status === 'OFF') {
                 var linkone = '</td><td><a href="#" class="btn btn-danger 
                    btn-xs"><i class="glyphicon glyphicon-off">
                      </i>'+admins[i-1].driver_status;
             } else if(admins[i-1].driver_status === 'BREAK') {
                 var linkone = '</td><td><a href="#" class="btn btn-default 
                  btn-xs"><i class="fa fa-coffee"></i>'+admins[i-
                  1].driver_status;
             } else {
                var linkone = '</td><td><a href="#" class="btn btn-warning 
                    btn-xs"><i class="glyphicon glyphicon-off">
                    </i>'+admins[i-1].driver_status;
             }               
            var driverid = admins[i-1].driverid;                
             var $formrow = '<tr><td><a id="'+admins[i-1].driverid+'" 
               onclick="myFunction2(this.id);" data-toggle="modal" data-
                 target="#myModal"  value="'+admins[i-
                1].driverid+'">'+admins[i-1].firstname+
             '</a></td><td>'+admins[i-1].lastname+
             '</td><td>'+admins[i-1].phonenumber+
             '</td><td>'+admins[i-1].vehiclenumber+
             linkone+                
             '</td><td>'+admins[i-1].loginstatus+
             '</td><td><a href="#" class="btn btn-success btn-
                  xs">'+admins[i-1].accountstate+'</a></td></tr>';
            $('#example').append($formrow);         
        }
        $(document).ready(function() {

            $('#example').DataTable();
        });



      <div class="table-responsive">
       <table id="example" class="display" cellspacing="0">
         <thead><tr><th>First Name</th><th>Last Name</th>
            <th>Phone Number</th><th>Vehicle Number</th><th>Duty Status</th>
            <th>Login Status</th><th>Account Status</th></tr>
         </thead>
      </table>
    </div>

 $('#example')
    .removeClass( 'display' )
    .addClass('table table-striped table-bordered');

Answer №1

Apply CSS styles to the tag as you loop through your data.

You can define CSS classes like these:

tr.highlighted {
    background-color: yellow;
}
tr.inactive {
    background-color: gray;
}

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

What is the best way to display live time on an HTML web page?

Hey there, on my website I have implemented 3 different flash clocks. All the clocks are currently working, but I now need to synchronize them with the real time. Is there a way to display the real clock time on an HTML webpage using JavaScript or jQuery? ...

Incorporating animation effects in ajax technology

I've coded a feature that utilizes the .getJSON API from jQuery to retrieve images from the Flickr public API. You can view it on this link. Each image slides after every request is completed. Now, I would like the initial set of images to slide downw ...

Looking for recommendations on JSON format for an AJAX response?

Suppose I submit a form through Ajax and am awaiting a response from the server: Pass/fail status If fails, a compilation of validation errors including corresponding field ids/names, etc Is there a widely adopted or recommended JSON format for organizi ...

"Sturdy Accordian Design: No Collapsing Issues with

Hello everyone, I'm attempting to recreate a collapsing accordion feature that I came across on https://getbootstrap.com/docs/4.1/components/collapse/. However, I'm facing issues as the accordions are not collapsing as expected. Strangely, they b ...

Tips for triggering both server side and client side events in ASP web forms

In an ASP.NET web form, I have the following code snippet: <asp:UpdatePanel ID="udpNames" runat="server"> <ContentTemplate> <div class="expanderheaders"> <asp:Image ID="epImgNames" ...

Can you locate the hiding spot of the express-session cookie?

After setting a very short cookie max-age (10 secs) in my express-session, I confirmed that it is working as expected: app.use(session({ secret: 'xxx', resave: false, saveUninitialized: true, cookie: { secure: true, maxAge: 10000 } })); ...

Is there a way in Node.js to showcase a list of choices using console log and prompt the user to input an option from the list displayed through console log?

Is there a way to use Node.js to show a list of options through the console log and prompt the user to input an option from the list via console log? Expected behavior user@desktop:~$ node test.js Option 1 Option 2 Option 3 Select an option to proceed: ...

Learning how to implement server side rendering in React JS through tutorials

After diving into the world of React js and mastering the basics, I successfully created web pages using this technology. I also honed my skills with node js and express. However, now I am faced with a new challenge: server side rendering. The tutorials av ...

Error in main thread: org.openqa.selenium.WebDriverException - $ is not defined

Acquiring a CSS selector by ID is resulting in an error when I invoke the getCSS method: UpdateActualPath actualPath= new UpdateActualPath(); actualPath.getCSS("https://www.google.co.in/", "a"); This is the code snippet: import java.io.IOException; ...

Prevent children from extending outside the boundaries of their parent

I am facing an issue with my page layout that includes a sidebar. The content in the sidebar is overflowing the page, so I attempted to use CSS properties like overflow-y: hidden and max-height: 100vh on the main element, as well as overflow-y: auto on the ...

Prevent the wrapping of table cells in CSS tables

I'm currently developing a board game in JavaScript, and I have stored the images for the board within a table structure. Initially, I used HTML <table> tags for this purpose. However, I later realized that since the table doesn't contain d ...

Get information from a specific text input after pressing the Enter key, among several text inputs with identical names and IDs

I am facing a challenge where I have multiple text inputs dynamically generated with the same id and name. My goal is to retrieve the data entered in a specific text input whenever a user hits the 'Enter' key in that field. For example, let&apos ...

javascript Arabic speech synthesis

Attempting to utilize SpeechSynthesisUtterance for Arabic language Successfully functioning with English content $(document).ready(function() { var u1 = new SpeechSynthesisUtterance('Hello world!'); u1.lang = 'en-US'; u1.pitch ...

Leveraging Swift's self within Javascript for interacting with Swift class properties and methods

In a project I am working on, I use a JS method called function jsMethod(selfRef) from a Swift class. Let's say we have a class A where this method is invoked. The selfRef parameter holds a reference to the instance of class A. How can I utilize this ...

The createAsyncThunk function doesn't provide the userId attribute in the returned data

I am currently working on retrieving data for appointments from my rails-api backend using the createAsyncThunk function. Here is a snapshot of the console log: console.log('appointmentDate', appointmentDate); console.log('doctorId', do ...

What is the best way to conceal an element solely in live production environments?

Is there a way in my Angular code to specifically target the PROD environment? <div *ngIf="environment !== 'prod'" class="col-6"> <button class="btn btn-primary text-white add-photo" (cli ...

Enhancing User Experience with Bootstrap V5 Form Validation and Sweetalert2: Displaying a Message of Success Upon Successful Submission

I am currently working on implementing a simple form using Bootstrap 5 that includes validation. My goal is to display an alert message when the form field is successfully submitted using Sweetalert2. Below is the code I have: HTML <form action=&q ...

When the webpage is reloaded in Internet Explorer, a file is automatically downloading. How can this issue be resolved?

Below is the anchor tag in HTML for downloading a file. <a [href]="myFileUrl" class="u-text--document" download="myfile.csv"><span>Title of the Excel document (6.8MB)</span></a> This method is called on n ...

Identify the client's network disconnection using socket.io in NodeJs

Currently, I am in the process of developing an application using node.js and socket.io. One of the requirements for my app is to be able to detect when the client-side connection to the internet is lost and then trigger a manual or automatic disconnection ...

After sending a test email, inline CSS in Gmail seems to be functioning to some extent

While working on applying inline CSS styling to HTML for email, I have encountered an issue where the styling partially works when sending a test email. Can anyone provide guidance on how to resolve this problem? Steps to reproduce: Step 1 - apply CSS st ...