我正在尝试计算多行的价格。我让它工作一行,但是,当我将它放入for循环时,onchange函数似乎不起作用。谁知道那是为什么?
JavaScritpt:
function cal()
{
var price = document.getElementById('priceper_0').value;
var per_pack = document.getElementById('per_pack_0').value;
var quantity = document.getElementById('quantity_0'.value;
document.getElementById('subtotal_0').value = ((price/per_pack)*quantity).toFixed(2);
}
PHP / HTML:
<table>
<tr>
<td>Paper</td>
<td align="center">Price</td>
<td align="center">Per Pack</td>
<td align="center">Quantity</td>
<td align="center">Sub Total</td>
</tr>
<tr class="multipp">
<td><input type="text" name="description_0" id="description_0" size="85" maxlength="70" value="<?php echo htmlspecialchars($description[0]); ?>" /></td>
<td><input type="text" name="priceper_0" id="priceper_0" size="10" maxlength="9" value="" /></td>
<td><input type="text" name="per_pack_0" id="per_pack_0" size="10" maxlength="9" value="" /></td>
<td><input type="text" name="quantity_0" id="quantity_0" size="10" maxlength="9" onChange="cal();"/></td>
<td><input type="text" name="subtotal_0" id="subtotal_0" class="txt" size="15" maxlength="9" value="" /></td>
</tr>
<?php
for($i=1; $i<10; $i++)
{
echo '<tr class="multipp">';
echo '<td><input type="text" name="description_'.$i.'" id="description_'.$i.'" size="85" maxlength="70" value="'.htmlspecialchars($description[$i]).'" /></td>';
echo '<td><input type="text" name="priceper_'.$i.'" id="priceper_'.$i.'" size="10" maxlength="9" value="'.htmlspecialchars($priceper[$i]).'" /></td>';
echo '<td><input type="text" name="per_pack_'.$i.'" id="per_pack_'.$i.'" class="txt" size="10" maxlength="9" value="'.htmlspecialchars($priceper[$i]).'" /></td>';
echo '<td><input type="text" name="quantity_'.$i.'" id="quantity_'.$i.'" size="10" maxlength="9" onChange="cal();" value="'.htmlspecialchars($quantity[$i]).'" /></td>';
echo '<td><input type="text" name="subtotal_'.$i.'" id="subtotal_'.$i.'" size="15" maxlength="9" value="'.htmlspecialchars($subtotal[$i]).'" /></td>';
echo '</tr>';
}
?>
</table>
最佳答案
原因是id问题,您应该对元素使用唯一的id
试试这个
将您的$i
传递给calc()
函数,然后执行以下函数
onChange=cal($i)
功能
function cal($i)
{
var price = document.getElementById('priceper_'+$i+'').value;
var per_pack = document.getElementById('per_pack_'+$i+'').value;
var quantity = document.getElementById('quantity_'+$i+'').value;
document.getElementById('subtotal_'+$i+'').value = ((price/per_pack)*quantity).toFixed(2);
}
关于javascript - 计算多行总价,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20283797/