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
1
  • 1
    Hello, Swadhin and Welcome to StackOverflow! For future questions, try to provide Minimal reproducible code: 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): stackoverflow.com/questions/10802244/… Nevertheless, your question is clear! You should look for jquery documentation api.jquery.com Commented Jan 27, 2023 at 0:34

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.