Home > OS >  How to sum the number from td tag using id with array
How to sum the number from td tag using id with array

Time:07-17

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 ?

CodePudding user response:

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>

CodePudding user response:

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

for example:

<td >200<td>
<td >400<td>
<td >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);
}
  • Related