Search code examples
javascripthtmlcalculated-columns

Calculate sum of last column in dynamically added rows using javascript


I have a table that a user can dynamically add a row as needed. I need to add a text box underneath the table that will dynamically output the total of the last column using JavaScript. If the calculations can't be done dynamically then I can add a calculate button underneath the text box

<HTML>
<HEAD>
    <TITLE> Add/Remove dynamic rows in HTML table </TITLE>
 
    <SCRIPT language="javascript">
function addRow(tableID) {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;
    if (rowCount < 4) { // limit the user from creating fields more than your limits
        var row = table.insertRow(rowCount);

        var colCount = table.rows[0].cells.length;
        row.id = 'row_'+rowCount;
        for (var i = 0; i < colCount; i++) {
            var newcell = row.insertCell(i);
            newcell.outerHTML = table.rows[0].cells[i].outerHTML;            
        }
       var listitems= row.querySelectorAll("input, select");
       
            for (i=0; i<listitems.length; i++) {
              listitems[i].setAttribute("oninput", "calculate('"+row.id+"')");
            }
          
    } else {
        alert("Maximum Passenger per ticket is 4.");

    }
}
function calculate(elementID) {
    var mainRow = document.getElementById(elementID);
    var myBox1 = mainRow.querySelectorAll('[name=qty]')[0].value;
    var myBox3 = mainRow.querySelectorAll('[name^=sel]')[0].value;
    var total = mainRow.querySelectorAll('[name=total]')[0];
    var myResult1 = myBox1 * myBox3;
    total.value = myResult1;

}
  

</SCRIPT>
</HEAD>
<BODY>
    
   <input type="button" value="Add" onClick="addRow('dataTable')" />

<table id="dataTable" class="form" border="1">
    <tbody>
        <tr id='row_0'>
            <p>
                <td>
                    <label>Quantity</label>
                    <input type="number" required="required" name="qty" oninput="calculate('row_0')">
                </td>
                
                <td>
                     <label for="sel">Price</label>                 
                    <select name="sel" id="sel" oninput="calculate('row_0')" required>
            <option value="" disabled selected>Choose your option</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
           </select>
                </td>
                <td>
                    <label for="total">Total</label>
                    <input type="text" required="required" class="small" name="total">
                </td>
            </p>
        </tr>
    </tbody>
</table>
</BODY>
</HTML>

Any help will be greatly appreciated.


Solution

  • Here try this.
    I added the sum in a tfoot first but the way you added new row made it awkward so I just put it in a div at the bottom of the table.

    <html>
      <head>
        <title>Add/Remove dynamic rows in HTML table</title>
    
        <script language="javascript">
          function addRow(tableID) {
            var table = document.getElementById(tableID);
            var rowCount = table.rows.length;
            if (rowCount < 4) {
              // limit the user from creating fields more than your limits
              var row = table.insertRow(rowCount);
    
              var colCount = table.rows[0].cells.length;
              row.id = "row_" + rowCount;
              for (var i = 0; i < colCount; i++) {
                var newcell = row.insertCell(i);
                newcell.outerHTML = table.rows[0].cells[i].outerHTML;
              }
              var listitems = row.querySelectorAll("input, select");
    
              for (i = 0; i < listitems.length; i++) {
                listitems[i].setAttribute("oninput", "calculate('" + row.id + "')");
              }
            } else {
              alert("Maximum Passenger per ticket is 4.");
            }
          }
          function calculate(elementID) {
            var mainRow = document.getElementById(elementID);
            var myBox1 = mainRow.querySelectorAll("[name=qty]")[0].value;
            var myBox3 = mainRow.querySelectorAll("[name^=sel]")[0].value;
            var total = mainRow.querySelectorAll("[name=total]")[0];
            var myResult1 = myBox1 * myBox3;
            total.value = myResult1;
    
            // calculate the totale of every total
            var sumContainer = document.getElementById("totalOfTotals");
            var totalContainers = document.querySelectorAll("[name=total]"),
              i;
            var sumValue = 0;
            for (i = 0; i < totalContainers.length; ++i) {
              sumValue += parseInt(totalContainers[i].value);
            }
            sumContainer.textContent = sumValue;
          }
        </script>
      </head>
      <body>
        <input type="button" value="Add" onClick="addRow('dataTable')" />
    
        <table id="dataTable" class="form" border="1">
          <tbody>
            <tr id="row_0">
              <p>
                <td>
                  <label>Quantity</label>
                  <input
                    type="number"
                    required="required"
                    name="qty"
                    oninput="calculate('row_0')"
                  />
                </td>
    
                <td>
                  <label for="sel">Price</label>
                  <select name="sel" id="sel" oninput="calculate('row_0')" required>
                    <option value="" disabled selected>Choose your option</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                  </select>
                </td>
                <td>
                  <label for="total">Total</label>
                  <input
                    type="text"
                    required="required"
                    class="small"
                    name="total"
                  />
                </td>
              </p>
            </tr>
          </tbody>
        </table>
        <div>
          <tr>
            <span>Sum</span>
            <span id="totalOfTotals">0</span>
          </tr>
        </div>
      </body>
    </html>