Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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;
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda