Note that in both cases, I used the subtotal2
as a reference, but logic serves any field. I also removed the short PHP tags (<?=
) , because they’re not portable, but it’s just a suggestion. The formatting of the fields in a monetary format with two houses is in charge of adjustments in the adopted solution (and already escapes a bit of the scope).
With Jquery:
// Código principal:
$(function() {
var soma = 0;
$( ".subtotal2" ).each( function() {
soma += Number( $( this ).html() );
} );
$( "#resultado" ).text( "R$ " + soma );
} );
<!-- Trecho HTML para demonstração: -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table>
<tr class="somatoria">
<td>Balao de borracha</td>
<td>12789</td>
<td>R$ <span class="subtotal1">29.00</span></td>
<td>1</td>
<td>R$ 2</td>
<td>R$ <span class="subtotal2">31.00</span></td>
</tr>
<tr class="somatoria">
<td>CD Maria do Relento</td>
<td>23419</td>
<td>R$ <span class="subtotal1">33.00</span></td>
<td>1</td>
<td>R$ 0</td>
<td>R$ <span class="subtotal2">33.00</span></td>
</tr>
<tr>
<td colspan="5">TOTAL</td>
<td id="resultado">?</td>
</tr>
</table>
With PHP:
<?php
$soma = 0;
while($M_P = mysql_fetch_array($Dados_Produtos)) {
$subtotal2 = $M_P['preco'] * $M_P['quantidade'] + $M_P['taxas'];
$soma += $subtotal2;
?>
<tr class="somatoria">
<td><?php echo utf8_encode($M_P['produto']); ?></td>
<td><?php echo $M_P['codigo']; ?></td>
<td>R$ <span class="subtotal1"><?php echo $M_P['preco']; ?></span></td>
<td><?php echo $M_P['quantidade']; ?></td>
<td>R$ <?php echo $M_P['taxas']; ?></td>
<td>R$ <span class="subtotal2"><?php echo $subtotal2; ?></span></td>
</tr>
<?php } ?>
<tr>
<td colspan="5"></td>
<td>R$ <?php echo $soma; ?></td>
If the value is dynamic, you can create an array in PHP to use by JS without the need for jQuery
– Papa Charlie