使用 javascript 计算动态添加行中最后一列的总和

Calculate sum of last column in dynamically added rows using javascript

我有一个 table,用户可以根据需要动态添加一行。我需要在 table 下面添加一个文本框,它将使用 JavaScript 动态输出最后一列的总数。如果无法动态完成计算,那么我可以在文本框下方添加一个计算按钮

<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>

任何帮助将不胜感激。

在这里试试这个。
我首先在 tfoot 中添加了总和,但是您添加新行的方式使它变得尴尬所以我只是将它放在 table.

底部的 div 中

<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>

我相信您想获得整个 table 中最后一列的总值。

那么我认为您需要迭代列。 使用下面的函数代码。

function totalvalues() {
  var table = document.getElementById("dataTable");
  var totalcellvalue = 0;
  for (var i = 0, row; row = table.rows[i]; i++) {
    //rows would be accessed using the "row" variable assigned in the for loop
    for (var j = 0, col; col = row.cells[j]; j++) {
      //columns would be accessed using the "col" variable assigned in the for loop
      if (j == 2) {
        //alert('col html>>'+col.children[1].value);
        totalcellvalue += parseInt(col.children[1].value);
      }
    }
  }
  console.log(totalcellvalue);
}

// And I have called the above method ```totalvalues()`` in your ```calculate()``` method.
<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;
      totalvalues();// calling my function here
    }
  </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="number" required="required" class="small" name="total">
          </td>
        </p>
      </tr>
    </tbody>
  </table>
</BODY>

</HTML>