开发者

How to program and calculate multiple subtotal and grandtotal using jquery?

I'm stump figuring out how to do this in jquery, I need to do it without any plug-in. Imagine a shopping cart for books, each change of quantity (using select dropdown) will update the total price, grandtotal and then the hidden input value.

<table>
<tr> 
    <td class="qty"> 
        <select class="item-1">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        ...
        </select>
    </td> 
    <td class="product"> 
        Book 1 
    </td> 
    <td class="price-item-1"> 
        $20
    </td> 
    <td class="total-item-1"> 
        $20
    </td> 
</tr>
<tr> 
    <td class="qty"> 
        <select class="item-2">
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
        ...
        </select>
    </td> 
    <td class="product"> 
        Book 2 
    </td> 
    <td class="price-item-2"> 
        $10
    </td> 
    <td class="total-item-2"> 
        $10
    </td> 
</tr>
...
...
<tr> 
    <td colspan="3" align="rig开发者_运维技巧ht"> 
        <strong>Grand Total:</strong> 
    </td> 
    <td class="grandtotal">
    </td> 
</tr> 
</table>

<input type="hidden" id="qty-item-1" value="0"  />
<input type="hidden" id="total-item-1" value="0"  />

<input type="hidden" id="qty-item-2" value="0"  />
<input type="hidden" id="total-item-2" value="0"  />


This should get you started:

$("select").change(function() {
    var qty = $(this).val();

    // get the price cell by moving up a level and searching for
    // the descendant with a class name beginning with `price'.
    // Remove the dollar sign to do math
    var price = $(this).closest("tr")
                       .find("td[class^=price]")
                       .html().split("$")[1];

    // a quantity is a whole number but a price is a float
    var total = parseInt(qty) * parseFloat(price);

    // write the total for this book to the 'total' cell
    $(this).closest("tr")
           .find("td[class^=total]")
           .html("$" + total);

    // sum up all the totals
    var grandTotal = 0;
    $("td[class^=total]").each(function() {
        grandTotal += parseFloat($(this).html().split("$")[1]); 
    });

    // update the grandtotal cell to the new total
    $(".grandtotal").html("$" + grandTotal);
});​

In other words, you need to:

1 - Get the quantity from the selected option's value.

2 - Get the price from the cell in the same row whose class begins with 'price', multiply that by the quantity, and update the 'total' cell of the same row.

3 - (Re)calculate the grand total (the sum of all totals) and put that value into the .grandtotal cell.

Try it here: http://jsfiddle.net/kYssr/4/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜