How to use Jquery to dynamically alter cell backgrounds in a table based on their values?

I successfully imported the table from MySQL to HTML, as shown below:

https://i.sstatic.net/kzJtF.png

My script is designed to highlight the two lowest and two highest values in each column:

    $(document).ready(function(){

var $table = $("#tbTodos");
  $table.find("th").each(function(columnIndex)
 {
var oldValue=0, currentValue=0;
var $trs = $table.find("tr");
var highElements = [];
var highElements2 = [];
var lowElements = [];
var lowElements2 = [];
var lowestValue = 999999;
var lowestValue2 = 999999;
var highestValue = 0;
var highestValue2 = 0;


$trs.each(function(index, element)
{
    oldValue= currentValue;
    var cell = $(this).find("td:eq("+ columnIndex +")");

    if (cell.length!=0) 
    {
        currentValue= parseInt(cell.html());
        if(currentValue < lowestValue)
        {
            if(currentValue < lowestValue2)
        {
                lowestValue2 = lowestValue;
                lowElements2 =lowElements.pop();
                //lowElements2.push((cell));
            }

            lowestValue = currentValue;
           // lowElements = [];
            lowElements.push(cell);
        }
        else if (currentValue == lowestValue) {
            lowElements.push(cell);
        }


        if (currentValue > highestValue)
        {
            highestValue2 = highestValue;
            highElements2 = highElements.pop();
         //   highElements2.push(highElements.push(cell));

            highestValue = currentValue;
      //      highElements = [];
            highElements.push(cell);
        }
        else if (currentValue == highestValue) {
            highElements.push(cell);
        }
    }
});


$.each(lowElements2, function(i, e){
    $(e).addClass('highest2');
});

 $.each(lowElements, function(i, e){
    $(e).removeClass('highest2').addClass('highest');
});

$.each(highElements2, function(i, e){
    $(e).addClass('lowest2');
});

 $.each(highElements, function(i, e){
    $(e).removeClass('lowest2').addClass('lowest');
   });

  });
});

CSS stylings:

    .highest{
      background-color:#ff4040;
        }
    .highest2{
    background-color:#f07878;
}
    .lowest{
    background-color:#66cc47;
}
    .lowest2{
    background-color:#aee59d ;
}

The highlighting for the first highest and lowest values in each column works correctly. However, there are discrepancies with the second highest and lowest values in some columns, such as 7 and 8. Additionally, the first column lacks a second-highest number.

View this on fiddle: https://jsfiddle.net/kaee715m/

Answer №1

const $table = $("#tbTodos");
$table.find("th").each(function(columnIndex){

    const values = [];

    const $tds = $table.find("td").filter(function(){
        return $(this).index() === columnIndex;
    });

    $tds.each(function(index, el){
        const val = parseInt($.trim($(el).text()));
        values.push(val);
    });

    values.sort((a, b) => {return b-a});

    $tds.each(function(index, el){
        const val = parseInt($.trim($(el).text())),
            cls,
            vl = values.length;

        if(val === values[vl-1])            cls = 'highest';
        else if(val === values[0])          cls = 'lowest';

        if(vl > 3 && val === values[vl-2])  cls = 'highest2';
        if(vl > 3 && val === values[1])     cls = 'lowest2';

        $(el).addClass(cls);
    });
});

Answer №2

Here is a straightforward method that involves creating a new array of columns, each containing a jQuery object for every cell in the column. This array is then iterated through to sort each column sub-array. This makes it simple to assign classes based on their position in the array.

As the sorting process occurs outside the DOM, it does not impact the actual element positions within the DOM structure.

var cols = []
// Populate cols arrays
$('tr:gt(0)').each(function(){  
  $(this).children().each(function(i){
     if(!cols[i]){
         cols[i]=[];
     }
     cols[i].push($(this));
  })
})

// Loop through columns
$.each(cols, function(_, cells){
   var len = cells.length;
   
   // Sort each column array
   cells.sort(function($a,$b){
     return (+$a.text()) - (+$b.text())
  });
  
  // Add classes based on position in sorted array
  cells[0].addClass('lowest');
  cells[1].addClass('lowest2');
  cells[len-1].addClass('highest')
  cells[len-2].addClass('highest2')
})

Please note that this method assumes all cells contain a numerical value.

DEMO

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

Combining two HTML tables in PHP: A step-by-step guide

I have two HTML tables that each contain three rows and one column. I am looking to combine them programmatically in order to create a single table with two columns and three rows. Is there a specific function or workaround that can help me achieve this? ...

Enhance your Magento store with a personalized layout update

Is there a way to call a stylesheet from my skin folder instead of pointing to my base path? Right now I have <reference name="head"> <action method="addCss"> <stylesheet>yourtheme/css/red.css</stylesheet> < ...

Generate a series of rotations ranging from -60 to 60 using d3.cloud

I need help replicating the word cloud feature found on for my website. After studying examples and referencing a Stack Overflow answer, I put together the following code: var fill = d3.scale.category20(); var layout = d3.layout.cloud() .size([900, ...

jQuery slider triggering a function with a consistent delay of 1 until the handle is released

I've been trying to figure out this issue for a while now and haven't found a solution yet. If you take a look at my project here, you'll see that the values at the top don't update correctly until the handle is released. I've been ...

What is the best way to conceal text while retaining icons on a compact screen?

How can I hide the text links for Home, Reservations, My Reservations, About, and Settings on smaller screens while still keeping the icons visible? Currently, I am using the following resources: http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.1 ...

Display the contents in a textarea with modal, not as a string

I'm currently working on implementing a modal overlay window with simplemodal that will display the contents of a text area. My goal is to show the rendered output rather than just the string value. For example, if a user enters HTML or includes an im ...

Tips for adjusting the width of a table

add your image description hereImagine a scenario where there is a table featuring two columns. <table> <tr><td>Email</td> <td></td></tr> <tr><td>Full name</td> <td></td></tr> ...

Incorporate the list seamlessly into the remaining content of the page

I am currently developing a Vue component that utilizes an API call to search for a list of cities based on user input. My challenge is ensuring that the displayed list does not overlap with the header component, specifically overlapping the image of the s ...

"Enhance your database by incorporating HTML link clicks through AJAX integration with PHP and MySQL

After browsing through similar questions and attempting to implement it on my website, I'm facing an issue where the expected functionality is not working as intended. When users click on a link, there is no response in the console, and the database r ...

Avoid multiple delays when clicking the identifier

I came across this code snippet: $(element).on('click', function() { $this.closest('div').before('<span id="message" style="display:none"></span>'); $('#message').fadeIn().delay(5000).fadeOut(); ...

The file upload issue with FormData append in CodeIgniter is causing errors

My current challenge involves uploading files using AJAX to my CodeIgniter based website. Unfortunately, I am encountering an issue where I cannot retrieve the file field value in the controller. This results in an error message stating "Undefined index: & ...

What is the correct way to create a template form in Django given the structure of my views.py file?

def ajax_lookup(request,channel): This particular view is essential for handling autocomplete functionality. The issue here lies in the JS code where an error occurs due to sending 1 attribute instead of the required 2. How can I successfully send the se ...

The outcome of the WCF Web Service shows an error of Unexpected Token Illegal - ParserError when using Chrome or IE9, but works fine

When I make an ajax request through jQuery, I am encountering a "SyntaxError: Unexpected token ILLEGAL" in Google Chrome and an "Unterminated string constant" error in IE9. Strangely enough, this function works perfectly fine in Firefox. The result output ...

Leveraging the Scroll feature in Bootstrap for smooth scrolling

Seeking assistance with implementing scroll in Bootstrap 5 on my child component (ProductList.vue). Can anyone guide me on how to integrate the code? I have been searching for a solution without success. Below is the Bootstrap 5 code on the child component ...

Using jQuery to send a post request to a servlet and then refreshing the parent

As I dive into the world of ajax jQuery documentation, my goal is to send a post call to a servlet that I have created in order to save an entry in my database. Once the post is successful, I aim to reload the parent of the iFrame responsible for rendering ...

Sorting functionality in Dyntable is not functioning properly when called from an Ajax request

I can't seem to get DynaTable with Ajax to work properly. Sorting, searching, and pagination are not functioning as expected. When I click on the column header, nothing changes in my table. Could someone please assist me? Below is my code snippet: H ...

How can I use JavaScript or CSS to identify the specific line on which certain words appear in the client's browser?

Imagine I have the following HTML structure: <div> <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco labor ...

How can I simplify the CSS properties for this border?

I created a div named "commentbox" and I want to apply a border with the color #ccc. However, I only want the left, top, and bottom sides of the div to be bordered, leaving the right side untouched. Thank you! ...

on clicking GTM, obtain a different child element

My HTML code is structured as follows: <div onclick="location.href='https://ford-parts-accessories.myshopify.com/products/ash-cup-coin-holder-with-lighter-element?refSrc=6748959244479&amp;nosto=productpage-nosto-1-fallback-nosto-1';&q ...

Tips for retrieving form data using $_POST from the same page after submission via $.ajax

On my index.php page, there is a form with a text field that I want to retrieve using $_POST. The issue arises because I am utilizing JQUERY AJAX on the same page. Specifically, I am using the $.ajax function to pass data to another PHP page. However, if I ...