'add total SUM of column in html table
I have an HTML table that I want to add a total of the price column.
I have done this with javascript, however, I'm having an issue where it's not adding the value after a decimal point e.g. 5.50
here is my js code
var tds = document.getElementById('quote').getElementsByClassName('tprice');
var sum = 0;
for(var i = 0; i < tds.length; i ++) {
sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
}
var total = sum.toFixed(2);
document.getElementById('totalprice').innerHTML += "£" + total;
Solution 1:[1]
Your script can benefit from a map and a reduce with casting to number rather than the parseInt you have which will remove all decimals
I use the unary plus here instead of parseInt/Float
let sum = 0;
const prices = [...document.querySelectorAll('#quote .tprice')]
.map(td => isNaN(td.textContent) ? 0 : +td.textContent); // an array of numbers
if (prices.length) sum = prices.reduce((a, b) => a + b); // reduced to a sum
document.getElementById('totalprice').innerHTML += "£" + sum.toFixed(2);
<table id="quote">
<tr>
<td class="tprice">15.50</td>
</tr>
<tr>
<td class="tprice">16.50</td>
</tr>
<tr>
<td class="tprice">17.50</td>
</tr>
<tr>
<td class="tprice">18.50</td>
</tr>
</table>
<span id="totalprice"></span>
Solution 2:[2]
Maybee try change this line:
sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
to
var value = parseFloat(tds[i].innerHTML);
sum += isNaN(value) ? 0 : value;
but better show example of HTML table with sample (NOT PRODUCTION!) data
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | zbyso |
