How to calculate these HTML table's columns?


When changing the input values, the rows are getting calculated, but I can’t wrap my head around having all rows and columns calculated when the table gets built.

Here is the function. What is within the else{} statement is what needs attention

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

Here is the Fiddle, in case you feel like killing this one.
Much appreciated!

I would rethink the solution here. I would create a two-dimensional array that represents the table. First dimension would be the number of rows and the second dimension would be the columns. Then, you would build the HTML table from the array dynamically when the page loads. As far as the totals go, you would have a function that updates the corresponding array value when a corresponding input is changed and then sum a row’s values to calculate each total.

Then, to have the page load with the totals, you would simply iterate through the two-dimensional array and update each row’s totals when the page loads.

EDIT: If you want to stick to your current design, you could do something like:

function sumInputs (row) {
 const inputsArr = [ ...row.querySelectorAll('.size_qty') ];
 return inputsArr.reduce((total, { value }) => total += parseFloat(value), 0);

function sum_row_qty(el) {
  if (el) {
    const currentRow = el.closest("tr");
    currentRow.querySelector('.qty').value = sumInputs(currentRow);

tableRows.querySelectorAll('tr').forEach(row => {
  row.querySelector('.qty').value = sumInputs(row);
1 Like

This is so neat! Being a beginner and self-taught is easy to get lost. Thanks a million!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.