[英]Add two or more form values to get a grand total
对于下面的php foreach循环中的每一行,此JavaScript函数都可以独立工作。 但是,我想将这两个独立的总数加在一起以获得一个总计,并在下面的DIV标签中显示它。 我不知道如何拨出这些款额,然后将它们加在一起。 总计应该随数量的每次更改而更新,就像当前金额一样。 目前,总价格仅反映一个金额,而不是总计。
<head>
<script type="text/javascript">
function update(iteration){
var qty = document.getElementById('qty_' + iteration).value;
// alert('quantity_' + iteration);
var price = document.getElementById('price_' + iteration).value;
price = price.substring(0, 7);
qty = parseInt(qty);
var amount = (qty * price).toFixed(2) ;
parseFloat(document.getElementById('amount_' + iteration).value = amount).toFixed(2);
//HERE's the code that's not working..
var subtotal;
for(var i =1; i < itemCount; i++) {
subtotal += document.getElementById('amount_' + i).value;
}
//this works
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Total $"+parseFloat(subtotal);
}
</script>
</head>
<?php
$listitems = unserialize($row["products"]);
$i=1;
foreach($listitems as $item)
{
echo '<tr><td>'.$item["code"].'</td><td><input type="number" id="qty_'.$i.'" name="qty_'.$i.'" min="1" size="3" value="1" onChange="iteration = '.$i.'; update(iteration); " /></td>';
echo '<td><input type="hidden" name="price_'.$i.'" id="price_'.$i.'" value="';
echo $item['price'];
echo '" />';
echo $item['price'];
echo '</td><td><input type="text" name="amount_'.$i.'" id="amount_'.$i.'" size="6" readonly value="';
echo $item['price'];
echo '"/></td></tr>';
$i++;
}
?>
<div id="totalPrice"></div>
夫妻俩伸出来。
parseInt()需要一个基数参数。
parseInt(qty, 10);
林对此行正在做什么感到困惑:
parseFloat(document.getElementById('amount_' + iteration).value = amount).toFixed(2);
parseFloat返回一个浮点,但是您是否将其设置为任何值?
导致您的错误的问题是var subtotal
声明。
您正在声明一个变量,其amount + itself
等于amount + itself
不存在。 您希望小计等于什么?
编辑:现在,您已经更新了,您想要迭代项目的数量并将其全部添加在一起。
var subtotal;
for(var i =0; i < itemCount; i++) {
subtotal += document.getElementById('amount_' + i).value;
}
这将迭代数量元素的0-itemCount。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.