Summary
- I am making a ordering form that will multiply “Qty of Items” by “Unit price” to give the “Subtotal” by JavaScript.
- The orders are stored in MySQL db and retrieved via PHP.
- I want to manually enter “Unit Price,” I wish after I type that number in the multiplication will happen.
- There are 10 rows of items (an array).
- All written code performs correctly as expected.
Problem
- My JavaScript function only runs for the first row, not any others.
- I want to run for every row, for each item type.
My Code
JS
function calc(){
baseprice=parseInt(document.getElementById("baseprice").value);
units=parseInt(document.getElementById("units").value);
x=baseprice*units;
document.getElementById("sub").value=x;
}
PHP / SQL
$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;
}
}
Sample Result / Situation

Extension
Making a grand total at the bottom right, adding all of the sub-totals fields as they are “onchange”.
subTotal=parseInt(document.getElementById("sub" + el.id.replace('baseprice', '')).value); document.getElementById("grandtotal")= subTotal+parseInt(document.getElementById("grandtotal").value);
An id has to be unique on a page, you have multiple input’s with the same id on the page. Hence why it is only every performing the calculation on the first input. Your best bet is to append a numerical value to ‘baseprice’ and ‘units’ input to distinguish each row. In addition pass the ‘this’ keyword into the calc function to reference the element that has triggered the function.
Example row:
JS: