How to program and calculate multiple subtotals and grandtotals using jquery?

I stump figuring out how to do this in jquery, I need to do it without any plugins. Imagine a basket of books, each change in quantity (use the dropdown to select) will update the total price, grant and then hidden input.

<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="right"> 
        <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"  />

      

+2


a source to share


1 answer


This should help you:

$("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:

1 - Get the quantity from the selected option value.



2 - Get the price from the cell in the same row whose class starts with "price", multiply it by the quantity and update the "total" cell of the same row.

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

.

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

+8


a source







All Articles