Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

62
Vistas
How to sum the number from td tag using id with array

I am trying to get a sum of numbers inside td tag and the tags have id=total[] which comes as an array. Example :

<td id="total[1]">200<td>
<td id="total[2]">400<td>
<td id="total[3]">500<td>
...etc

How do I get the sum of all of them using the id ?

6 months ago · Santiago Gelvez
2 Respuestas
Responde la pregunta

0

If there is no particular reason for you to use id, it is better to use class.

for example:

<td class="foo">200<td>
<td class="foo">400<td>
<td class="foo">500<td>
...etc

Then you can add the values by looping over the elements:

var items = document.getElementsByClassName("foo");
var sum = 0;

for (var i = 0; i < items.length; i++) {
    sum += parseFloat(items.item(i).innerHTML);
}
6 months ago · Santiago Gelvez Denunciar

0

Jquery example for your HTML

$(document).ready(function(){
    var Sum = 0;
    $("[id*=total]").each(function(){
          Sum += parseFloat($(this).text());
    });
  $("#ttl").text(Sum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
 <td id="total[1]">200<td>
 <td id="total[2]">400<td>
 <td id="total[3]">500<td>
</table>
 Total: <span id="ttl"></span>

6 months ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos