Reputation: 107
I'm having a trouble on how can I get the total amount column based on the status. Currently I only manage sum all of my amount column. The thing is I want to get the value of sum amount of paid
and unpaid
amount status, for example like the image below the Paid
total should 15000
and the Unpaid
should 10000
. It would be great if anybody could figure out where I am doing something wrong. thank you so much in advance
var tds = document.getElementById('table').getElementsByTagName('td');
var sum = 0;
for(var i = 0; i < tds.length; i ++) {
if(tds[i].className == 'count-me') {
sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
}
}
document.getElementById('table').innerHTML += '<tr><td>' + sum + '</td><td>total</td></tr>';
<table id="table">
<tr>
<th >Status</th>
<th >AMOUNT</th>
</tr>
<tr>
<td >Paid</td>
<td class="count-me">5000</td>
</tr>
<tr>
<td >Paid</td>
<td class="count-me"> 5000</td>
</tr>
<tr>
<td >Unpaid</td>
<td class="count-me">5000</td>
</tr>
<tr>
<td >Unpaid</td>
<td class="count-me">5000</td>
</tr>
<tr>
<td >Paid</td>
<td class="count-me">5000</td>
</tr>
</table>
Upvotes: 4
Views: 1889
Reputation: 6610
There are many ways. This is one of them:
var tds = document.getElementById('table').getElementsByTagName('td');
var sum = 0;
var sumPaid = 0;
var sumUnpaid = 0;
for(var i = 0; i < tds.length; i ++) {
if(tds[i].className == 'count-me') {
sumPaid += tds[i-1].innerHTML == 'Paid' ? +tds[i].innerHTML : 0;
sumUnpaid += tds[i-1].innerHTML == 'Unpaid' ? +tds[i].innerHTML : 0;
sum += isNaN(tds[i].innerHTML) ? 0 : parseInt(tds[i].innerHTML);
}
}
document.getElementById('table').innerHTML += '<tr><td>' + sum + '</td><td>total</td></tr>';
document.getElementById('table').innerHTML += '<tr><td>' + sumPaid + '</td><td>total paid</td></tr>';
document.getElementById('table').innerHTML += '<tr><td>' + sumUnpaid + '</td><td>total unpaid</td></tr>';
<table id="table">
<tr>
<th >Status</th>
<th >AMOUNT</th>
</tr>
<tr>
<td >Paid</td>
<td class="count-me">5000</td>
</tr>
<tr>
<td >Paid</td>
<td class="count-me"> 5000</td>
</tr>
<tr>
<td >Unpaid</td>
<td class="count-me">5000</td>
</tr>
<tr>
<td >Unpaid</td>
<td class="count-me">5000</td>
</tr>
<tr>
<td >Paid</td>
<td class="count-me">5000</td>
</tr>
</table>
I hope this is just like a homework or something. In a real application you don't do things this way. You make these kind of computations BEFORE rendering the page or using somekind of framework as a help.
I think a good advice would be for you to start learning to do things like they are done theses days with a framework like React or Angular, or even better with functional programming.
Upvotes: 3