function calc(){
baseprice=parseInt(document.getElementById("baseprice").value);
units=parseInt(document.getElementById("units").value);
x=baseprice*units;
document.getElementById("sub").value=x;
}
$alter=0;
//previous miscellaneous code
while($rows=mysql_fetch_array($sql))
{
$alter=$alter+1;
//edit
$subCalc="<td><input name='units_".$alter."' id='units_".$alter."' type='hidden' value=".$rows['SUM(pizza_orders.qty)']."><input name='baseprice_".$alter."' id='baseprice_".$alter."' type='text' size='2' onchange='calc(this);'></td><td><input name='sub_".$alter."' id='sub_".$alter."' type='text' size='3'></td></tr>";
//alternates the table row colour by modulus
if ($alter %2 ==0){
echo "<tr><td>".$rows['item_order']."</td>";
echo "<td>".$rows['SUM(pizza_orders.qty)']."</td>".$subCalc;
}else{
echo "<tr class=\"alt\"><td>".$rows['item_order']."</td>";
echo "<td>".$rows['SUM(pizza_orders.qty)']."</td>".$subCalc;
}
}
在右下角创建一个总计,添加所有小计字段,因为它们是“onchange”。
subTotal=parseInt(document.getElementById("sub" + el.id.replace('baseprice', '')).value); document.getElementById("grandtotal")= subTotal+parseInt(document.getElementById("grandtotal").value);
答案 0 :(得分:1)
页面上的id必须是唯一的,页面上有多个具有相同ID的输入。因此,为什么只有每一个都在第一个输入上执行计算。您最好的选择是将数值附加到“baseprice”和“units”输入以区分每一行。另外,将'this'关键字传递给calc函数,以引用已触发函数的元素。
示例行:
<tr>
<td>
<input id="units_1" name="units_1" type="hidden" value="10" />
<!-- attach an onchange handler to baseprice_1, when a change is made trigger the calc function. -->
<input id="baseprice_1" name="baseprice_1" type="text" onchange="calc(this);" />
<input id="sub_1" name="sub_1" type="text" />
</td>
</tr>
JS:
/* An array to store the subtotals. */
grandTotalArr = [];
function calc(el){
/* el = this (which is a reference to baseprice_1) */
baseprice=parseInt(el.value);
units=parseInt(document.getElementById("units" + el.id.replace('baseprice', '')).value);
x=baseprice*units;
document.getElementById("sub" + el.id.replace('baseprice', '')).value=x;
/* Store the subtotal in the grandTotalArr using it's id as the key. */
grandTotalArr["sub" + el.id.replace('baseprice', '')] = x;
/* Implode all values with the + operator, and evaluate as a JS expression. Once evaluated, update the grand total. */
document.getElementById('grand_total').value = eval(grandTotalArr.join('+'));
}