I am creating a simple shopping cart prototype and want to make a JavaScript array that will take the quantity of each table row, multiply it by the price, and display the total in the final column. The quantity value is a form where the user inputs the quantity. I would also like to include a table row with the grand total. I have these two functions but I am wondering how I can make one function work for the entire table:
<script type="application/javascript">
function total()
{
var qty = document.forms["qty"]["amount"].value;
var sum1 = qty * 5.99;
document.getElementById("total1").innerHTML="$" + sum1;
}
</script>
<script type="application/javascript">
function total2()
{
var qty2 = document.forms["qty2"]["amount2"].value;
var sum2 = qty2 * 105.99;
document.getElementById("total2").innerHTML="$" + sum2;
}
</script>
The table
<table id="cart">
<tr>
<th><b>Quantity</b></th>
<th><b>Item</b></th>
<th>Price</b></th>
<th><b>Total</b></th>
</tr>
<tr>
<td><form name="qty"><input type="number" name="amount" size="1" value="1" onchange="total1()"/></form></td>
<td>Product 1</td>
<td>$5.99</td>
<td id="total1"></td>
</tr>
<tr>
<td><form name="qty2"><input type="number" name="amount2" size="1" value="1" onchange="total1()"/></form></td>
<td>Product 2</td>
<td>$105.99</td>
<td id="total2"></td>
</tr>
<tr>
<td><b>Grand Total<b></td>
<td id="grand"></td>
</tr>
</table>