Note that in both cases, I used subtotal2
as a reference, but the logic is for any field. I also removed the short PHP tags ( <?=
) since they are not portable, but it is a mere suggestion. The formatting of the fields in monetary format with two houses is in charge of adjustments in the adopted solution (and already it escapes a lot 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><trclass="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>