1

I'm using a script to generate a new row with value each time, those values goes to a table as an input All what I want is a button to sum all values in those inputs in one input.

Total input id is valueall

This is the code I have used:

            function updateSubTotal() { 
            var table = document.getElementById("empTable");
            for (var i = 0, row; row = table.rows[i]; i++) {
                for (var cell; cell = row.cells[1];){
                var inp = cell.children[0];
                }
             }     
             document.getElementById("valueall").value = inp.value;
            }  

That code works fine when I put it under var inp = cell.children[0]; but it keeps repeating the same row value as loop.

Here's the table:

 <form>
        <table id="empTable">
            <tr>
                <td>Products in the invoice</td>
            </tr>
        </table>
 </form>
Samir Junaid
  • 109
  • 2
  • 10
  • Does this answer your question? [How do I iterate through table rows and cells in JavaScript?](https://stackoverflow.com/questions/3065342/how-do-i-iterate-through-table-rows-and-cells-in-javascript) – kmoser Aug 10 '21 at 19:48
  • @kmoser Unfortunately I already saw that answer, it doesn't work with inputs (children). – Samir Junaid Aug 10 '21 at 19:58

1 Answers1

1

You're not summing anything. You need to actually sum up the contents of the <input> fields:

function updateSubTotal() { 
  var sum = 0;
  var table = document.getElementById("empTable");
  for (var i = 0, row; row = table.rows[i]; i++) {
    for (var cell; cell = row.cells[1];){
      var inp = cell.children[0];
      sum += Number(inp.value)
    }
  }     
  document.getElementById("valueall").value = sum;
}
kmoser
  • 8,780
  • 3
  • 24
  • 40