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

Javascript Looping With Sum Operation

I want to Loop a NAFAG field and sum every NAFAG field with a scheme like this. Every time I repeat the NAFAG sum, the result should be added to the KNAFA field

  • 0 + -30000 results to the 2nd row KNAFA field
  • 0 + -30000 + -30000 results to the 3rd row KNAFA field
  • 0 + -30000 + -30000 + -30000 results to the 4th row KNAFA field
  • 0 + -30000 + -30000 + -30000 + -30000 results to the 5th row KNAFA field

enter image description here

can anyone help me with this loop.

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 :

I hope my code help you.

HTML

<table>
  <thead>
    <th>KNAFA</th>
    <th>NAFAG</th>
  </thead>
    <tbody>
    </tbody>
</table>

Javascript

let nafag = [0, -3000, -3000,-3000,-3000,-3000, -3000];
let sum = 0;
for (const elem of nafag) {
    sum += elem;
  let elements = "<tr><td>" + sum + "</td><td>" + elem + "</td></tr>";
  var parent_tbody = document.getElementsByTagName("tbody");
 
  var new_tr = document.createElement('tr');
  new_tr.innerHTML = elements;
  parent_tbody[0].appendChild(new_tr);
}

Result


KNAFA   NAFAG
0       0
-3000   -3000
-6000   -3000
-9000   -3000
-12000  -3000
-15000  -3000
-18000  -3000
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