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 a the value after a decimal point e.g. 5.50
here is my js code
<script language="javascript" type="text/javascript">
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;
</script>
CodePudding user response:
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
CodePudding user response:
Your script can benefit from a map and a reduce with casting to number rather than parseInt
let sum = 0;
const prices = [...document.querySelectorAll('#quote .tprice')]
.map(td => isNaN(td.textContent) ? 0 : td.textContent)
if (prices.length) sum = prices.reduce((a, b) => a b);
document.getElementById('totalprice').innerHTML = "£" sum.toFixed(2);
<table id="quote">
<tr>
<td >15.50</td>
</tr>
<tr>
<td >16.50</td>
</tr>
<tr>
<td >17.50</td>
</tr>
<tr>
<td >18.50</td>
</tr>
</table>
<span id="totalprice"></span>
