0

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.

  • Are you want a `total` of `total column` below that column is that right ??? or something else – Rabby Oct 14 '20 at 06:09
  • It's not clear what you want exactly, can you explain better? What do you want to calculate exactly? – Oussama Bouthouri Oct 14 '20 at 06:11
  • Firstly, you need to add a `tfoot` section into your `table` tag (create it **above** the `tbody` tag but it will appear below it on the page). Then your `calculate()` function needs to also loop through all of the rows and get the total, which is then put into a cell on the new `tfoot` row. You could also have a global variable to hold the total and simply update that with the new value and refresh the `tfoot` cell. – ATD Oct 14 '20 at 06:21
  • @WaytoDeveloper yes total of the total column – Mjwebdevloper Oct 14 '20 at 06:28
  • @OussamaBouthouri yes, sure I want sum of total colum which is dynamically added – Mjwebdevloper Oct 14 '20 at 06:30
  • @ATD can you write the code because I dont understand exactly. thank you! – Mjwebdevloper Oct 14 '20 at 06:31

2 Answers2

0

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>
Oussama Bouthouri
  • 615
  • 2
  • 8
  • 23
0

I believe you want to get a total value of last column throughout the table.

Then I think you need to Iterate through column. Using below function code.

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>