JSFiddle - React, Tailwind, and code Playground

by Torwan

HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<table class="tally">
    <tr>
        <th>name</th>
        <th>sum1</th>
        <th>sum2</th>
    </tr>
    <tr>
        <td>balance</td>
        <td>100</td>
        <td>200</td>
    </tr>
    <tr>
        <td>gains</td>
        <td>20</td>
        <td>40</td>
    </tr>
    <tr>
        <td>loses</td>
        <td>-36</td>
        <td>60</td>
    </tr>
    <tr class="sum">
        <td>Total</td>
        <td class="col1 sum">#</td>
        <td class="col2 sum">#</td>
    </tr>
</table>

JavaScript

$( document ).ready(function() {
    do_sums();
});

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));
            }
        })
    });
}