我有一个文本框的 javascript 代码,根据客户购买的物品数量和每个物品的总金额动态添加。金额乘以每个数量。我不能做的是把它们全部加起来。我如何实现它?我使用了一个while循环,但它只返回了最后一项。我知道逻辑,我只是不知道如何保存每个项目的总金额,然后将其添加到下一个项目中。希望有人能帮忙。谢谢。
function totalBillItem(rowcount){
var quantity = parseFloat($("#quantity"+rowcount).val());
var payment_interval = parseFloat($("#payment_interval").val());
var billing_price = parseFloat($("#billing_price"+rowcount).val());
var product = (quantity * billing_price).toFixed(2);
$("#total"+rowcount).val(product);
while(rowcount != 0) {
var sub_total = parseFloat($("#total"+rowcount).val());
rowcount--;
}
var grand_total = sub_total;
$("#grand_total").val(grand_total);
}
我的 HTML:
<table class="table table-striped table-hover" id="myTable">
<tr>
<th style="text-align:center;background-color:#89CFF0;">Name</th>
<th style="text-align:center;background-color:#89CFF0;">Product Price</th>
<th style="text-align:center;background-color:#89CFF0;">Quantity</th>
<th style="text-align:center;background-color:#89CFF0;">Billing Price</th>
<th style="text-align:center;background-color:#89CFF0;">Total</th>
</tr>
<?php
$row_count=0;
$offset=0;
foreach( $data as $row ) :
$dta = unserialize($row->userdata);
?>
<tr class="info">
<td style="text-align:center;" id="prod_name<? echo $row_count; ?>"><?php echo $dta['product_name']; ?></td>
<td style="text-align:center;" id="product_amount<? echo $row_count; ?>"><?php echo $dta['product_amount']; ?></td>
<td style="text-align:center;">
<input type="text" name="quantity<? echo $row_count; ?>" id="quantity<? echo $row_count; ?>" class="span2" onkeydown="totalBillItem('<?php echo $row_count; ?>')" onkeyup="totalBillItem('<?php echo $row_count; ?>')" value="0">
</td>
<td style="text-align:center;">
<input type="text" name="billing_price<? echo $row_count; ?>" id="billing_price<? echo $row_count; ?>" class="span2" onkeydown="totalBillItem('<?php echo $row_count; ?>')" onkeyup="totalBillItem('<?php echo $row_count; ?>')" value="0">
</td>
<td style="text-align:center;">
<input type="text" name="total<? echo $row_count; ?>" id="total<? echo $row_count; ?>" class="span2" readonly>
</td>
</tr>
<input type="hidden" name="prod_uuid<? echo $row_count; ?>" value="<? echo $dta['product_uuid']; ?>">
<input type="hidden" name="prod_amount<? echo $row_count; ?>" value="<? echo $dta['product_amount']; ?>">
<?php
$row_count++;
endforeach;
?>
<input type="hidden" name="row_ctr" value="<? echo $row_count; ?>">
</table>
<br />
Total:
<input type="text" name="grand_total" id="grand_total" class="span2" readonly>
我怎么能这样做?http://jsfiddle.net/c4rjk/