Using jQuery to sum the values in a table column

May, 09 2012

Here is some neat jQuery based off of this post [naspinski.net] that lets you sum up the values in a HTML table.

In general I would definitely use a different, usually database centric, approach to summing values. On the page I am currently working on though, there are going to be over 10 tables which are only useful with sums. As it is I am going to be doing many queries for this page, and it will be alright that the summing is a bit delayed.

First the HTML:

<table class="tally">
        <th>balance</th>
        <td>100</td>

    <tr>
        <th>gains</th>
        <td>20</td>
    </tr>
    <tr>
        <th>loses</th>
        <td>-36</td>
    </tr>
    <tr class="sum">
        <th>Total</th>
        <td class="sum">#</td>
    </tr>
</table>

This will render a table with some values and "#" where the total should be. With some jQuery powered javascript we can do the summing:

function sumOfColumns(table, columnIndex) {
    var tot = 0;
    table.find("tr").children("td:nth-child(" + columnIndex + ")")
    .each(function() {
        $this = $(this);
        if (!$this.hasClass("sum") && $this.html() != "") {
            tot += parseInt($this.html());
        }
    });
    return tot;
}

function do_sums() {
    $("tr.sum").each(function(i, tr) {
        $tr = $(tr);
        $tr.children().each(function(i, td) {
            $td = $(td);
            var table = $td.parent().parent().parent();
            if ($td.hasClass("sum")) {
                $td.html(sumOfColumns(table, i+1));
            }
        })
    });
}

You can use some css with the class "sum" to highlight your sums to make your tables easier to read. This should work with different types of tables, including summing multiple columns at once. Unfortunately, it won't work with tables which use colspans or rowspans.


Tweet comments, corrections, or high fives to @amjoconn