Reputation: 235
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:
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.
Upvotes: 2
Views: 1264
Reputation: 5069
See if this is what you had in mind: 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>
$(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);
});
})
Upvotes: 1