JQuery: sum of values of a column

1

I have a problem with JQuery, I do not understand why it adds up well sometimes and sometimes badly.

My code to calculate is as follows:

var sum=0;
$('.subtotal').each(function() {  
 sum += parseFloat($(this).text());  
}); 
$('#resultado_total').val(sum.toFixed(2));

My table is as follows:

<table class="table table-condensed table-hover table-striped ">
<tr>
<th class='text-center'>Estado </th>
<th class='text-right'>Total</th>
</tr>
<tr>
<td class='text-center'><?php echo $estado;?></td>
<td class='text-right subtotal'><?php echo number_format($total,2);?></td>
</tr>
</table>

Waiting for your support! thanks in advance!

    
asked by JBAL27 27.06.2018 в 21:16
source

2 answers

0

The problem is the comma in the numbers. You must eliminate it and then add. Something like this:

var sum=0;
$('.subtotal').each(function() {  
 sum += parseFloat($(this).text().replace(/,/g, ''), 10);  
}); 
$('#resultado_total').val(sum.toFixed(2));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<table class="table table-condensed table-hover table-striped ">
<tr>
<th class='text-center'>Estado </th>
<th class='text-right'>Total</th>
</tr>
<tr>
<td class='text-center'></td>
<td class='text-right subtotal'>550.00</td>
</tr>
<tr>
<td class='text-center'></td>
<td class='text-right subtotal'>1,050.00</td>
</tr>
</table>
<input type="text" id="resultado_total"></input>
    
answered by 27.06.2018 / 21:36
source
0

How could the sum be by state? I have 3 states, "PAID", "MUST" and "CANCELED". Currently I have the totalized general.

Result: Total Global: XXX, Total Paid: XXX, Total Must: XXX, Total Voided: XXX

gracis in advance!

    
answered by 29.06.2018 в 19:22