Loop through each row in the table's body with
$('#balance_table > tbody > tr').each(function() {
}
Loop through each column in the current row with
cols.each(function(index, val) {
}
Write sum in the last column.
Demo:
var sum = 0;
$('#balance_table > tbody > tr').each(function() {
var cols = $(this).find('td');
cols.each(function(index, val) {
// sum all columns except last column (balance)
var isLast = index == cols.length - 1;
var isDebit = index == 0;
var isCredit = index == 1;
if (isLast) {
// see https://stackoverflow.com/questions/980821/jquery-each-method-obscures-this-keyword
var jQueryObject = $(val);
jQueryObject.text(sum);
} else {
sign = isCredit ? -1 : 1;
sum += sign * parseFloat(val.textContent);
}
})
});
table,
td {
border: 1px solid gray;
}
thead,
tfoot {
background-color: gray;
color: #fff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="balance_table">
<thead>
<tr>
<td>debit</td>
<td>credit</td>
<td>balance</td>
</tr>
</thead>
<tbody>
<tr>
<td>100</td>
<td>0</td>
<td>-</td>
</tr>
<tr>
<td>0</td>
<td>150</td>
<td>-</td>
</tr>
<tr>
<td>0</td>
<td>200</td>
<td>-</td>
</tr>
<tr>
<td>200</td>
<td>0</td>
<td>-</td>
</tr>
</tbody>
</table>
See also:
Hope this helps!