Doing calculations in an HTML table?

Hi there, I’m wondering if we can use an HTML table for calculations like in a spreadsheet. I seem to remember that it was possible to reference various cells in a table and use the data there to calculate (e.g. add them up) the results in another cell. Can someone tell me where I might find out how to do this?

Hi there, Randell. Many thanks for your answer and suggestion. I was hoping to download some scripts and learn from there, rather than write them from scratch. Thank you also for the suggestion to use contenteditable. I am not familiar with this attribute but I assume that all it does is to make the cell editable by the user. Actually, I wasn’t planning to make the table usable in that sense but to write code within the HTML where I can use one cell to calculate data from other cells. Also, your answer does not solve my fundamental query about how to reference other cells in the same table within the HTML code. Nevertheless, I am grateful for your prompt reply.

Hey @Mackie10,

HTML table doesn’t have superpowers of a spreadsheet, I’m afraid that’s something you have to provide with JavaScript or external libraries yourself.

Yes, but I’m hoping to learn from what other people have done as well… Thank you for your input.

The most basic implementation can be achieved by selecting the portion of the table you need, then loop on the content, perform your calculation then output.

Assuming you have something like:

// html
	<table>
		<tr>
			<td>3</td>
			<td>4</td>
		</tr>
		<tr>
			<td>1</td>
			<td>0</td>
			<td>14</td>
		</tr>
		<tr>
			<td>5</td>
			<td>8</td>
			<td>2</td>
			<td>3</td>
		</tr>
	</table>

A very basic table with some rows you can

// select the Nodes
const tableRows = document.querySelectorAll('tr');

// loop over each row
tableRows.forEach(row => {
    // select each cell in the current row node
    let cells = row.querySelectorAll('td')
   // get ready to store each individual value
    const allTheValues = []
    
   // loop over each cell and extract the content into our array
    cells.forEach(cell => allTheValues.push(parseInt(cell.innerHTML, 10)));

   // compute the values, in this example sum
    const total = allTheValues.reduce((acc, val) => acc + val, 0);

   // display the output: add a new <td> with the total in it.
    row.insertAdjacentHTML('beforeend', `<td>sum: ${total}</td>`)
  })

Hope this gives you some starting points :+1: