0

I have this table

debit credit balance
100 0
100 0
0 150
0 200
200 0

I want the following balance column using datatable jquery or api .Please help me. Thanks in advance.

debit credit balance
100 0 100
100 0 200
0 150 50
0 200 -150
200 0 50
user2314737
  • 27,088
  • 20
  • 102
  • 114
  • 1
    Hello, Swadhin and Welcome to StackOverflow! For future questions, try to provide [Minimal reproducible code](https://stackoverflow.com/help/minimal-reproducible-example): If we can copy/paste it into our machine, it's good! Then, make sure the title is a question, it clarifies the problem and makes it searchable. For example: how to sum two columns in Jquery? To which google answers (it might be your solution): https://stackoverflow.com/questions/10802244/sum-total-for-column-in-jquery Nevertheless, your question is clear! You should look for jquery documentation https://api.jquery.com/ – Florian Fasmeyer Jan 27 '23 at 00:34

1 Answers1

1

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!

user2314737
  • 27,088
  • 20
  • 102
  • 114