Changing the color scheme of a row depending on the data in the table cell

I've been working on changing the color of table rows based on the text contained in one of its cells. Specifically, I want a row to turn red if the cell contains the value "Failed." However, only one row is behaving as expected.

Below is the code I'm using:

CSS:

<style>    
   .failed {
       background: red !important;
       color: white !important;
   }
</style>

HTML:

<table class="table table-striped">
    <thead>
        <tr>
            <th class="text-center">#</th>
            <th>Session Eamil</th>
            <th>Login Url</th>
            <th>Date</th>
            <th>Status</th>
            <th></th>
        </tr>
    </thead>
    <tbody>
        @{ var counter = 1;}
            @foreach (var item in Model)
            {
                <tr>
                    <td class="text-center">@counter</td>
                    <td>@item.SessionEmail</td>
                    <td>@item.LoginUrl</td>
                    <td>@item.CreatedAt.ToLocalTime().ToString("G")</td>
                    <td>@item.Status</td>
                    <td class="text-center">
                        <a href='@Url.Action("JobDetail","ArchivedScrapeJob", new{jobId=item.Id})'><span class="glyphicon glyphicon-option-horizontal" aria-hidden="true"></span></a>
                    </td>
                </tr>
        counter++;
            }
    </tbody>
</table>

JS Code:

<script>
    $(function() {

        $(".table-striped").find("tr").each(function () {
            $("td").filter(function() {
                return $(this).text() === "Failed";
            }).parent().addClass("failed");
        });
    });
</script>

The goal is to dynamically change the row color depending on the value of the cell (if it's "Failed"). You can view the actual output here: https://i.sstatic.net/M5Dqg.jpg

This issue has been resolved.

Answer №1

Is it possible to establish the classification within the razor script?

<tr class="@(item.Status == "Failed" ? "failed" : "")">

Answer №2

Avoid using JavaScript code for this task. Simply include the status class directly on the tr tag.

<tr class='@item.Status'>

.Failed {
    background: red;
    color: white;
}

Answer №3

Make sure to assign a class to the status column.

<td class="status">@item.Status</td>

Then, include this script in your code:

<script>
    $(function() {

        $(".table-striped").find("tr").each(function () {
           var status= $(this).find(".status").html();  
           if(status=="Failed")
             {
                    $(this).addClass("failed")
             }
        });
    });
</script>

Give it a try and see if it works!

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 AddClass function does not work properly in the Kendo Tree View after the RemoveClass function, especially when selecting the same node

Hey there, I am currently working with a kendoTreeView and trying to set up an action triggered by clicking on the same selected node. To achieve this, I incorporated the following code in the change event: change : function(e) { $ ...

Ways to ensure CSS affects icon inside main element?

Struggling to match the background color of Material-UI icons with the rest of the list items on hover. The CSS is not applying to both the icon and text despite styling the overall class (className= "dd-content-item"). Any assistance would be greatly appr ...

Ensuring Quick Response Times When Incorporating Personalized Text Styles into Twitter Bootstrap

Currently, I am experimenting with incorporating my custom class titled "article-title" which is significantly larger than the default H1 font size in Twitter Bootstrap. Can someone provide guidance on the necessary steps to ensure responsiveness? My goal ...

Ensuring elements are correctly positioned

I am struggling to make the images in the following code align horizontally across the top and also need to align the h1's in the same way. I have tried using the vertical-align property, but it seems to behave oddly to me. HTML: <div class=&apos ...

Choose a random item from a dynamic array within an HTML document

I am looking to enhance a Google Site by enabling users to click a button that will reveal a random letter of the alphabet. The catch is that it should only randomize letters selected by the user via checkboxes. In the image below, you can see what I am ai ...

Why does my ajax call always send a GET request instead of a POST?

$.ajax({ type:"post", url: server_url, dataType: "jsonp", jsonpCallback: callback, data:req_json, cache: false, timeout: 60000, success: succeeded, error: got_error }); I've ...

Tips for applying a CSS class with a smooth fade-out effect

In my Angular project, I am working on creating a custom notification component. Here is the template code I have so far: <aside *ngFor="let message of messages "> <div class="notification" style="position:fixed"> {{message.conten ...

What is the best way to conduct automated tests on CSS rendering across various browsers, including Safari Mobile and the Android Browser?

Is there a way to programmatically and automatically test how CSS is rendered in various browsers, similar to how Selenium tests HTML and Javascript across different browsers? It would be great to integrate this with a BDD framework. ...

The second attempt at an AJAX call is unsuccessful

I am currently developing a form that displays database results based on two entries: Automarke (brand) and Modell (model). You can view the entries here. The Modell dropdown dynamically changes based on the selected Automarke. Here is the code snippet I ...

What is causing the color property to not accept CSS gradients?

Is there a way to create text with a gradient color effect? I've noticed that gradients don't work on the color property. Is there another method to achieve text with gradient colors? ...

Toggling the form's value to true upon displaying the popup

I have developed an HTML page that handles the creation of new users on my website. Once a user is successfully created, I want to display a pop-up message confirming their creation. Although everything works fine, I had to add the attribute "onsubmit= re ...

Can Webpack effectively reduce the size of jQuery files?

While this question may seem basic, I have yet to come across a direct answer to it. My dilemma is whether or not to continue utilizing jQuery in my React application, primarily for AJAX purposes. Will webpack intelligently include only the necessary AJA ...

The Angular application is not displaying correctly on mobile devices due to a lack

Having an issue with my angular build. I've deployed my website at this link: It appears fine when viewed on a desktop and even in the devtools. However, when I try to access it on my phone, the layout looks terrible! Any suggestions on how to fix ...

How can I retrieve PHP code output within a jQuery function?

In my CodeIgniter project, I am trying to generate a unique ID using PHP by calling the random_string() function: function coding(){ echo random_string('unique'); } I want to use the result of this function in an AJAX jQuery call (to be use ...

I am having trouble getting React to properly render my components when using the router

As a newcomer to React, I am currently working on my first website. Despite researching online for solutions, I have not been able to find an exact answer to my particular issue. The layout of my components is in a scroll-down style (portfolio), but when ...

Should the use of Url.Action in HTML/JavaScript blocks be considered a best practice from an MVC perspective?

Following a discussion in the comments section of this particular question, I found myself pondering - is it considered good practice to utilize Url.Action in JavaScript blocks within views to access the same routes defined in RouteConfig rather than hardc ...

Alignment and spacing that is responsive and inline for unordered lists

Struggling with creating a mobile-responsive navbar, specifically with getting the link containers to resize correctly and centering the text vertically. Attempts with padding and margins haven't yielded results. Bootstrap is being used. In need of a ...

Incorporate fresh selections into an already established custom autocomplete feature in real time

Is it possible to dynamically insert a label into current categories using jQuery UI custom autocomplete? I have implemented a customized autocomplete following the example outlined here in the jQuery UI documentation: <html lang="en"> <head> ...

Sending image id as a parameter to a MySQL query in PHP using jQuery

Having trouble passing image ids to mysql queries. I've tried the following code but keep getting an Undefined index x error. I've checked multiple Stack Overflow answers without success. echo "<img src=http://localhost/ss/img/".$p['pat ...

Using jQuery to display items retrieved from multiple ajax requests in a sequential order

When I have a page with listings of objects that are fetched using ajax calls, how can I ensure they are rendered in sequence? I attempted the method demonstrated here, but if one request fails, it rejects the rest. Since my data is not dependent on each ...