• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

114
Views
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 ?

about 3 years ago · Santiago Gelvez
2 answers
Answer question

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);
}
about 3 years ago · Santiago Gelvez Report

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>

about 3 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error