Using HTML and CSS to Dynamically Alter Cell Text Color Based on Value

Unfortunately, I am unable to find a straightforward solution. My goal is to adjust the text color inside my cell based on its value.

Here is a basic table:

<table>
  <tbody>
    <tr>
      <td>Quantity</td>
      <td>1</td>
    </tr>
  </tbody>
</table>

My criteria for formatting are as follows:

  • If the number is 1, it should display in yellow
  • If the number is greater than 1, it should display in red

I came across this code, but unfortunately, I'm unable to integrate it into my file at the moment. Thank you for your understanding.

$('#mytable tr td').each(function(){

    if($(this).text() > 1)$(this).css('background-color','red');
});

Is there any alternative suggestion for addressing this issue?

Furthermore, what if my table includes other numeric cells like this one:

<table>
  <tbody>
    <tr>
      <td>Price</td>
      <td>20</td>
    </tr>
    <tr>
      <td>Quantity</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

Is it possible to apply the code selectively only to certain cells?

I need to implement these modifications by editing the Prestashop MailAlert module that sends order confirmation emails.

In mailorder.php, I will need to incorporate the condition for changing the color of the quantity cell.

The email will be generated using the new_order.html file, which serves as the email template and fetches data from mailorder.php.

Where should I insert the script code? I can provide excerpts from the relevant files if necessary. Thank you.

Answer №1

You can use the parseFloat function to determine if a value is a number. If it is, you can then apply styling based on the value:

$('#mytable tr td').each(function(){
  var cellValue = $(this).html();
  if(!isNaN(parseFloat(cellValue))) {
    if (cellValue > 1) {
      $(this).css('background-color','red');
    } else {
      $(this).css('background-color','yellow');
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable">
  <tbody>
    <tr>
      <td>Quantity</td>
      <td>1</td>
    </tr>
    <tr>
      <td>Quantity</td>
      <td>3</td>
    </tr>
    <tr>
      <td>Quantity</td>
      <td>2</td>
    </tr>
  </tbody>
</table>

Answer №2

Feel free to test out this code snippet and make any necessary adjustments to the code and script based on your preferences.

$('#mytable tr td').each(function(){
  var cellValue = $(this).html();
  if(!isNaN(parseFloat(cellValue))) {
    if (cellValue == 1) {
      $(this).css('background-color','red');
    } 
    
    if(cellValue==2){
     $(this).css('background-color','green');
     }
     
         if(cellValue==3){
     $(this).css('background-color','blue');
     }
     
              if(cellValue==4){
     $(this).css('background-color','yellow');
     }
  }
});
table tr td
{
padding:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable" border="1" style="border-collapse:collapse;">
  <tbody>
    <tr>
      <td>Quantity</td>
      <td>1</td>
    </tr>
    <tr>
      <td>Quantity</td>
      <td>3</td>
    </tr>
    <tr>
      <td>Quantity</td>
      <td>2</td>
    </tr>
    <tr>
      <td>Quantity</td>
      <td>1</td>
    </tr>
    <tr>
      <td>Quantity</td>
      <td>3</td>
    </tr>
    <tr>
      <td>Quantity</td>
      <td>2</td>
    </tr>
  </tbody>
</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

Setting up the php/MVC framework on a server

Currently, I have developed a project using HTML/PHP and need guidance on uploading it to the server. My knowledge of servers is limited, but I do understand that the first page should be an index.php or index.htm file placed in the public_html folder. How ...

Ensure that icons are evenly spaced, regardless of whether they display a notification badge or not

Although not as abundant as depicted in the image below, it is more evident that I am seeking a couple of font awesome icons overlaid with a bootstrap badge to display notifications. The two issues that I am encountering are: There is excessive spacing ...

"Learn how to deactivate the submit button while the form is being processed and reactivate it once the process is

I have been searching for solutions to this issue, but none seem to address my specific concern. Here is the HTML in question: <form action=".."> <input type="submit" value="download" /> </form> After submitting the form, it takes a ...

The stacking order of elements is not affected by the z-index property when using absolute positioning

I have developed a unique custom toggle switch component with the following structure: <template> <div> <label class="switch"> <input type="checkbox" :checked="value" @c ...

What is the best way to design versatile div containers that combine the float property with fluid dimensions?

I am attempting to achieve a specific layout where the width of the content_container extends up to the right side of the screen and dynamically adjusts based on whether the expandable pane is collapsed or expanded. Applying width: 100% to .content_contain ...

What is the best way to access JSON stringified objects in PHP?

I recently used the following code snippet to send data to the server, but now I'm stuck on how to retrieve the array that was returned using PHP. Any suggestions would be greatly appreciated. $('.ticket-row').each(function() { tickets.push ...

Implementing template loading on page load with state in AngularJS

When my application loads, I want the nested view list-patents.htm to be displayed. The main navigation is on my index.htm, featuring two nav items: transactions and patents. If you click on patents, two sub-menu items will appear: list patents and add p ...

Mastering the art of manipulating arrays with jquery

Trying to implement a dynamic search bar feature using jQuery. Here is the code snippet: Fiddle : https://jsfiddle.net/fpLf1to4/ var inputSearch = $('.searchInput').hide(); var searchArray = ['s','e','a',& ...

Continuous Div Carousel with Looping in jQuery

I have developed a basic carousel to cycle through a series of divs, but I am facing some issues. I want the carousel to loop continuously so that after reaching "slide 07," it goes back to "slide 01." Unlike using a carousel plugin, I prefer having an ove ...

Lazy Loading fails to deliver for Ajax Requests

I recently integrated lazy loading following David Walsh's advice (tip 1) and it initially worked perfectly. However, I encountered an issue when the images were filtered and reloaded with an ajax request. The website is built on Rails, and the images ...

Incorporating an HTML/Javascript game into a reactJS website: A step-by-step

After developing a game using plain javascript and HTML along with a few JS libraries, I find myself inquiring about the process of integrating this game into my ReactJS website. Typically, the game is initiated by opening the index.html file located with ...

Tips for extracting an SVG path from HTML structure

This example I'm referencing is by Chris Coyer <svg version="1.1" xmlns="http://www.w3.org/2000/svg" mlns:xlink="http://www.w3.org/1999/xlink" style="display: none;"> <defs> <g id="icon-image"> <path class="path1" d="M0 4v26h32v ...

Converting an array to an object using underscore: a beginner's guide

My array consists of different subjects: var subject = ["Tamil", "English", "Math"]; Now, I want to transform this array into an object, structured like this: [{ "name": "Tamil" }, { "name": "English" }, { "name": "Math" }] ...

Trouble with Displaying HTML Table in Bootstrap 4.3.1 Tooltip

Struggling for hours to set up a custom HTML table in a tooltip box, I finally found that the Bootstrap version solves the issue. Surprisingly, it works perfectly under Bootstrap 4.0.0 but fails under Bootstrap 4.3.1. Could this be a bug or am I overlooki ...

Optimized layout for screen resolutions exceeding 1000 pixels wide

As I work on making my website responsive using Dreamweaver CC, I'm encountering a problem with screen sizes larger than 1000px. In Dreamweaver, there are three options for responsive web design at the bottom: desktop 1000px and less, tablet 768px an ...

Utilize conditional styling along with hover effects in ReactJS

I'm facing an issue where I need to set up a conditional style and a hover effect for TableRows. They work fine individually, but when combined, the hover function stops working. CSS const StyledTableRow = withStyles((theme) => ({ root: { tab ...

What is the best way to activate a post function using a hyperlink?

I'm struggling to figure out how to call my post function using a link within my navbar. The issue is that I'm working with links in the navbar code, and not sure how to integrate calling the post function with them. Below is the code for my pos ...

Vanilla JS Rock, Paper, Scissors Game - Fails to reset classes upon restarting

Many questions have been raised about this particular topic, but a solution for vanilla js seems elusive. Let's delve into a new challenge: Rock paper scissors with vanilla js. The game functions properly on its own, but the issue arises when attemp ...

What is the best way to eliminate the space between the website's border and the image?

Is there a way to eliminate the space between the left and right borders? I want the picture to fill 100% of the browser window. https://i.stack.imgur.com/gqgOs.png img.test { display: block; outline: 0px; padding: 0px; margin: 0px; } <img c ...

Excessive Expansion of Website Width

Initially, I crafted a website on my local server, and it had the ideal width. Afterwards, I uploaded it to the live server and made some design modifications. To my surprise, there is now an unexpected scroll bar at the bottom of the page, causing the s ...