2

I'm working on a web application and want to create something like an invoice calculation, but with sub-groups, so at the end I need the result of the group-totals and the sub-totals.

This is what I got so far: Fiddle

$(function() {
    $("#items").keyup(function(event) {
        var total = 0;
        $("#items .targetfields").each(function() {
            var qty = parseInt($(this).find(".quantity").val());
            var rate = parseInt($(this).find(".rate").val());
            var subtotal = qty * rate;
            $(this).find(".subtotal").val(subtotal);
            if (!isNaN(subtotal)) total += subtotal;
        });
        $("#total").html(total);
    });
})

Ultimately, I'm working towards something like this:

enter image description here

I have found a lot of examples about invoice calculation but not with groups or sub-totals.

I hoped someone could help me out with a little example.

4

1 回答 1

1

看看这是不是你的想法:http: //jsfiddle.net/yaMRQ/23/

<table class="items">
    <tr class="targetfields"> 
        <td><input type="text" name="quantity" class="quantity" /></td>
        <td><input type="text" name="rate" class="rate" size="5" /></td>
        <td><input type="text" name="sub_total" class="subtotal" /></td> 
    </tr> 
    <tr class="targetfields"> 
        <td><input type="text" name="quantity" class="quantity" /></td>
        <td><input type="text" name="rate" class="rate" size="5" /></td>
        <td><input type="text" name="sub_total" class="subtotal" /></td> 
    </tr>
    <tr>
        <td>Group:</td>
        <td colspan="2" align="right" class="g_total"></td>
    </tr>
</table>
<table class="items">
    <tr class="targetfields"> 
        <td><input type="text" name="quantity" class="quantity" /></td>
        <td><input type="text" name="rate" class="rate" size="5" /></td>
        <td><input type="text" name="sub_total" class="subtotal" /></td> 
    </tr> 
    <tr class="targetfields"> 
        <td><input type="text" name="quantity" class="quantity" /></td>
        <td><input type="text" name="rate" class="rate" size="5" /></td>
        <td><input type="text" name="sub_total" class="subtotal" /></td> 
    </tr>
    <tr>
        <td>Group:</td>
        <td colspan="2" align="right" class="g_total"></td>
    </tr>
</table>
<br/>---<br/>Total: <span id="total"></span>

​</p>

$(function() {
    $(".items").keyup(function(event) {
     var total = 0;
     $(".items").each(function(){
         var gtotal = 0;
         $(this).find(".targetfields").each(function() {
             var qty = parseInt($(this).find(".quantity").val());
             var rate = parseInt($(this).find(".rate").val());
             var subtotal = qty * rate;
             $(this).find(".subtotal").val(subtotal);
             if(!isNaN(subtotal))
                 gtotal+=subtotal;
         });
         $(this).find(".g_total").html("EUR "+gtotal); 
         total+=gtotal
     });
     $("#total").html("EUR "+total);
    });
})​
于 2012-11-28T16:14:43.517 回答