Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading