0

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>
4

2 に答える 2

0

You could set an id for each table and pass it to the function:

<script type="application/javascript">
function total(i, value)
{
    var qty = document.forms["qty" + i]["amount" + i].value;
    var sum1 = qty * value;
    document.getElementById("total" + i).innerHTML="$" + sum1;
}
</script>

So, call total('1', '5.99') and total('2', '105.99') at onChange.

With JQuery it is easier using 'this' + selector

于 2012-12-12T22:41:41.183 に答える
0

Remove the inline onchange event from both number type inputs and paste following code inside head tags between script tags

(function grandTotal()
{
    var cart=document.getElementById('cart'),
    forms=cart.getElementsByTagName('form'), total=0;
    for(var i=0;i<forms.length;i++)
    {
        var amount=forms[i].getElementsByTagName('input')[0];
        var qty=amount.value;
        var tr=forms[i].parentNode.parentNode;
        var price=tr.getElementsByTagName('td')[2].innerHTML.substr(1);
        total+=parseFloat(qty)*parseFloat(price);
        amount.onchange=grandTotal;
    }
    document.getElementById('grand').innerHTML=total.toFixed(2);
})();

Example Here.

于 2012-12-12T23:31:22.537 に答える