Hi

This may not be a php matter but i'm wondering if it can be done?

I have a table like the following:

<table>
<tr>
<td>1</td>
<td>2</td>
</tr>

<tr>
<td>7</td>
<td>9</td>
</tr>

<tr>
<td><<SUM OF THIS COLUMN (8)>></td>
<td><<SUM OF THIS COLUMN(11)>></td>
</tr>
</table>

I hope you understand what it is im asking. This is easy to do in mysql however can it be done in standard html/dhtml ?

Thanks

Dani AI

Generated

As noted, plain HTML cannot perform calculations by itself. As and suggested, do the math either when generating the HTML on the server (PHP) or on the client with JavaScript. The following is a compact, reliable client-side approach: it skips footer rows, reads text from each row cell at a given column index, strips non-numeric characters, parses numbers safely, and writes the total to a footer cell.

function sumTableColumn(tableSelector, colIndex) {
  const table = document.querySelector(tableSelector);
  if (!table) return 0;
  const rows = table.querySelectorAll('tbody tr, tr');
  let sum = 0;
  rows.forEach(row => {
    if (row.closest('tfoot')) return; // skip tfoot
    const cell = row.cells[colIndex];
    if (!cell) return;
    const raw = (cell.textContent || cell.innerText).trim();
    const cleaned = raw.replace(/[^0-9\.\-\,]/g, ''); // remove currency/letters
    const normalized = cleaned.replace(/,/g, ''); // remove thousands commas
    const val = parseFloat(normalized);
    if (!isNaN(val)) sum += val;
  });
  return sum;
}

document.addEventListener('DOMContentLoaded', () => {
  const total = sumTableColumn('#myTable', 0);
  const out = document.querySelector('#myTable tfoot td.total');
  if (out) out.textContent = total;
});

Notes and cautions: strip formatting consistently or keep a raw numeric value in a data- attribute and read cell.dataset.value to avoid parsing issues. For currency, sum integer cents (or use a decimal library) to avoid floating-point rounding, then format for display. If the table is editable or updated dynamically, recalc on input/change events or use a MutationObserver. For authoritative totals (billing, reporting), calculate on the server as well to prevent client-side tampering.

Recommended Answers

All 2 Replies

if the data values were populated by PHP and the HTML gnerated by PHP, the sums can be calculated with a for loop.

if this is just a plain HTML somefile.html, then at best you can use clientside scripting like javascript to traverse the table DOM and get the .value of the td, do a sum and then set the .value again for the final row.

just with html its not possible use javascript or php for calculation. if you need help about javascript or php calculation let me know.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.