Categories
Tutorials

Conditionally Formatting HTML Table

Formatting HTML tables is a way to make the part of existing data easy to identify by highlighting it with colors and other font adjustments. Today we are looking to highlight certain cell based on their value or formula.

The structure of our code will be same as we used in last article where we discussed Calculatating Auto Sum functionality. In fact we are building on top of the previous article.

So let’s start with the HTML structure (I have collapsed the snipped below, clicking on it will expand it)

<table id="income">
  <thead>
    <tr>
      <td>S.No</td>
      <td>Description</td>
      <td>Amount</td>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1.</td>
      <td>First Month Income</td>
      <td>500</td>
    </tr>
    <tr>
      <td>2.</td>
      <td>Second Month Income</td>
      <td>440</td>
    </tr>
    <tr>
      <td>3.</td>
      <td>Next Month Income</td>
      <td>500</td>
    </tr>
    <tr>
      <td>4.</td>
      <td>Next Month Income</td>
      <td>330</td>
    </tr>
    <tr>
      <td>5.</td>
      <td>Next Month Income</td>
      <td>205</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td></td>
      <td>Total</td>
      <td id="display-total">???</td>
    </tr>
  </tfoot>

</table>

<button onclick="formatMax()">Format Max</button>

The only thing that’s new here is a button which calls a JavaScript function formatMax() on click. Next we are going to cover what is in the formatMax function.

CSS

thead,tfoot{font-weight: bold;}
thead tr td:nth-child(2){
  width: 200px;
}
.max{
  background: green;
  color: white;
}

Our demo so far:

Conditionally Format Html table

Formatting Maximum Value:

I will shed some light on the core function of this tutorial before introducing some JavaScript magic. We are calculating Income for each month and to appeal it even better we will add the color green. The higher the value the higher will be the intensity or percentage of a color. For instance the highest value is 500 so it will more distinctive that the others. Following is the snapshot of finished of tutorial which is followed by how it’s done.

Finished Demo of conditionally fomatting a cell

 

 

 

 

 

 

Let’s Code

var tb = document.getElementById('income'),
  tbody,
  subtotal = [];

function retrieveAllValues() { ....
}

We are grabbing the table that contains the data and giving it a reference of variable  tb. Then variable tbody is declared for later use which will contain body of the table and last but not least there is empty array goes with the name of subtotal which will contain all the values of the last column of the table. Next we are going to discuss the retrieveAllValues() function.

  tbody,
  subtotal = [],

function retrieveAllValues() {
  for (var i = 0; i < tb.children.length; i++) {
    if (tb.children[i].tagName === 'TBODY') {
      tbody = tb.children[i];
    }
  } //loop ends after finding tbody inside the whole table


  for (var j = 0; j < tbody.children.length; j++) {
    var el = tbody.children[j];
    for (var k = 0; k < el.children.length; k++) {
      if (k == 2) {
        subtotal.push(el.children[k].innerText);
      } 
    } // End of tr loop that ends after finding last cell with in each row
  } // End of tbody loop that loop over each table row inside
} // retrieveAllValues functions ends here

From line 4 to line 9 we are just looping through all elements inside of our table and getting hold of tbody because we are not interested in thead or tfootTBODY is assigned to global variable tbody. The for loop with internal variable j on line 12 is looping over the kids of tbody which in this case are bunch of rows, and the one with internal variable is going through all the td’s untill it reaches to the end. Line 16 is line for which we have done all of this workload in this function. It grabs the values in the current cell and push or add it the global array subtotal.

Utility Function

  subtotal = [],
  total = 0;

function retrieveAllValues() { /...
}

function getMaxOfArray(array) {
  return Math.max.apply(null, array);
}

Unfortunately JavaScript doesn’t comes with a function to calculate maximum value in an array just like we have subtotal.length to calculate the length of any given array. We do have Math Object for the rescue. Function getMaxOfArray accepts an array and returns a maximum value.

Final Pieces

function retrieveAllValues() { /...
}
 
function getMaxOfArray(array) { /...
}

function formatMax() {
  retrieveAllValues();
  maxValue = getMaxOfArray(subtotal);

  for (var j = 0; j < tbody.children.length; j++) {
    var el = tbody.children[j];

    for (var k = 0; k < el.children.length; k++) {
      if (k == el.children.length-1) {
        // cVal holds the value of current cell
        var cVal = el.children[k].innerText;
        if (cVal == maxValue) {
          el.children[k].classList.add('max');
        } else {
          var percent = cVal / maxValue * 100;
          el.children[k].style.background = "linear-gradient(90deg, green ,white " + percent + "%)";
        }
      }
    } // End of tr loop that ends after finding last cell with in each row
  } // End of tbody loop that loop over each table row inside
}

Line 8 and Line 9 of the code are doing prerequisite job for FormatMax() function. FormatMax() is also function that is hooked to Format Max HTML Button. MaxValue has now maximum in the array which is populated one by one with the help of retriveAllValues function. The code from Line 7-15 is already explained in the retriveAllValues function.

Line 15 tells if this is the last cell of the row than checks whether it’s the maximum value or not (this comparison is done precisely on line 18). If it’s the maximum value than we just add it a class of max. The else block calculates percentage based on current value to the maximum value, followed by the usage of linear gradient to style the current html element.

The linear gradient starts with green color, a white color stop is applied based on percentage. All of the above code and theory can best explained by running following codepen demo. Just hit the Format Max  button and you are good to go.

See the Pen Conditionally Format HTML table by Samiullah Khan (@samiullah1989) on CodePen.6143

Conclusion

Every story need to have an end, likewise we are to the very end of this article. There will be room for improvement code refactoring wise may it can be much easier with totally different approach but I tried to illustrate the idea of Conditionally Formatting with minimum knowledge of JavaScript. Here not only loop but inner loops are effectively used. Hope you guys have find enough to learn from it. If you have a better idea or if this tutorial doesn’t work for you, shoot me with your messages in comment section.

Formatting is best seen on spreadsheet apps and that’s why this article is born.

 

One reply on “Conditionally Formatting HTML Table”

I wish you could add a video tutorial explaining step by step. It’s much easier to follow video guide.
Anyway great content

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.