Home > Back-end >  How to sum table columns and rows using JQuery?
How to sum table columns and rows using JQuery?

Time:09-29

The function below does calculate when a number changes in each row, but at start up, I'd like to have it calculate all columns and rows and put the total of each row.

function sum_row_qty(el) {
  let rowTotal = 0
  if (el) {
    let parent = el.closest("tr")
    parent.querySelectorAll('.size_qty').forEach(function(e) {
      rowTotal  = parseFloat(e.value)
    })
    parent.querySelector('.qty').value = rowTotal
  }
  /*else {
     $("#tableRows tr").each(function(row) {
         let sizes = row.querySelectorAll('.size_qty').forEach(function(e) {
           rowTotal  = parseInt(sizes);
         });
       }
     }*/
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody id="tableRows">
  <tr>
    <td><input  type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this)"></td>
    <td><input  type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this)"></td>
    <td><input type="number" min="0"  name="numberInputs" value="" readonly="true"></td>
  </tr>
  
  
  <tr>
    <td><input  type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this);"></td>
    <td><input  type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this);"></td>
    <td><input type="number" min="0"  name="numberInputs" value="" readonly="true"></td>
  </tr>
</tbody>
</table>

Thanks in advance!

CodePudding user response:

In the else block, call your function in a loop over an input in each row of the table.

Then call your function with no argument when the page is loaded, and it will execute this branch.

function sum_row_qty(el) {
  let rowTotal = 0
  if (el) {
    let parent = el.closest("tr")
    parent.querySelectorAll('.size_qty').forEach(function(e) {
      rowTotal  = parseFloat(e.value)
    })
    parent.querySelector('.qty').value = rowTotal
  } else {
    document.querySelectorAll("#tableRows > tr > td:first-child input").forEach(sum_row_qty);
  }
}

window.addEventListener("load", () => sum_row_qty());
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tbody id="tableRows">
    <tr>
      <td><input  type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this)"></td>
      <td><input  type="number" min="0" name="numberInputs" value="2" onchange="sum_row_qty(this)"></td>
      <td><input type="number" min="0"  name="numberInputs" value="" readonly="true"></td>
    </tr>


    <tr>
      <td><input  type="number" min="0" name="numberInputs" value="6" onchange="sum_row_qty(this);"></td>
      <td><input  type="number" min="0" name="numberInputs" value="3" onchange="sum_row_qty(this);"></td>
      <td><input type="number" min="0"  name="numberInputs" value="" readonly="true"></td>
    </tr>
  </tbody>
</table>

  • Related