Category: jQuery

How To: Change table cell color depending on its value using jQuery

Here’s a nifty trick using jQuery on how to iterate on all rows of a table except the first row,
how to get the value of a column in the current row being iterated and how to change the table cell color depending on the value it contains.

In
this case we wanted to change the color of the 3rd column depending on
whether it is higher or lower than the second column. There are two examples in here. The first one is select the table via its ID and the second version is selecting the table based on its class name.

Below is the full source for this sample:


Iterating to the table via table id

Product Name Yesterday Today
Egg 1.95 2.10
Sugar 1.92 1.88
Milk 1.95 1.97
beans 3.15 3.06

Iterating to the table via class name

Product Name Yesterday Today
Egg 1.95 2.10
Sugar 1.92 1.88
Milk 1.95 1.97
beans 3.15 3.06

You can copy and paste the code above and put it on a new file to see it running or you can view this sample running here: jquery_change_table_cell_color_depending_on_value.html
(3.05 KB)

HTH

How To: Change the row and column colors of a table using jQuery

Here’s a quick and easy way to alternate the row colors of a table using jQuery

The resulting code will apply the to the table and would look like this:

Basically what the code is doing is that it is selecting a css class called “report-table-horizontal” and applies the style to the tr attribute of the table based on their row index whether they are even or odd.

Now if you want to change the color of a  table column you can do so using this script:

The difference on this code is the third line wherein we specified that the style will be applied on the first td element of the table. Alternately you can use the nth-child(n) selector instead to do the same task:

Hope this helps. You can view the live sample here:
alternating table colors with jquery.html (2.42 KB)

or just copy and paste the HTML code below to a new file: