Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html table: adding a class to the highest value of each column

Is there any way to find the highest value of each column (in a html table) and to add a class to it using js or jQuery?

Note: the table is build with <thead> and <tbody>

The table looks like this:

  <table>
    <thead>
      <tr>
        <th class="age">age</th>
        <th class="success">success</th>
        <th class="weight">weight</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>20</td>
        <td>30%</td>
        <td>70.5kg</td>
      </tr>
      <tr>
        <td>30</td>
        <td>40%</td>
        <td>80.9kg</td>
      </tr>
      <tr>
        <td>13</td>
        <td>60%</td>
        <td>20.53kg</td>
      </tr>
      <tr>
        <td>44</td>
        <td>80.44%</td>
        <td>20kg</td>
      </tr>
    </tbody>
  </table>

Codepen

like image 508
mat Avatar asked Feb 19 '23 16:02

mat


2 Answers

FIDDLE - http://jsfiddle.net/tariqulazam/esfj9/

JAVASCRIPT

var $table = $("#mytable");
$table.find("th").each(function(columnIndex)
{
    var oldValue=0, currentValue=0, $elementToMark;
    var $trs = $table.find("tr");
    $trs.each(function(index, element)
    {
        $(this).find("td:eq("+ columnIndex +")").each(function()
        {
            if(currentValue>oldValue)
               oldValue = currentValue;
            currentValue = parseFloat($(this).html());
            if(currentValue > oldValue)
            {
                $elementToMark = $(this);
            }
            if(index == $trs.length-1)
            {
              $elementToMark.addClass("highest"); 
            }
        });
    });
});​

CSS

.highest{
    color:Red;
}​
like image 120
Tariqulazam Avatar answered Feb 21 '23 06:02

Tariqulazam


​Here's the JSFiddle I made:JSFiddle

Here's the function, using jQuery

function MarkLargest() {
    var colCount = $('th').length;
    var rowCount = $('tbody tr').length;
    var largestVals = new Array();

    for (var c = 0; c < colCount; c++) {
        var values = new Array();
        for (var r = 0; r < rowCount; r++) {
            var value = $('tbody tr:eq(' + r + ') td:eq(' + c + ')').text();
            value = value.replace("%", "").replace("kg", "");
            values.push(value);
        }
        var largest = Math.max.apply(Math, values);
        largestVals.push(largest);

        $('tbody tr').each(function() {
            var text = $(this).find('td:eq(' + c + ')').text();
            text = text.replace("%", "").replace("kg", "");
            if (text == largest) {
                $(this).find('td:eq(' + c + ')').addClass("max");
            }
        });
    }

    return largestVals[column];
}

$(function() {
    MarkLargest();
})​
like image 43
sbonkosky Avatar answered Feb 21 '23 05:02

sbonkosky