Question

I'm currently writing a small plugin for computer repair techs and I'm now trying to code the invoice section but not having much luck!

I've got the fields being populated from the database but I'm trying to use jquery to update the line totals and the total of the invoice.

Heres a quick image of what I'm trying to do!

enter image description here I'm trying to get it to update the totals on pageload and when a value changes in the unit cost and quantity textfields.

$(document).ready(function() {
    $("#invoiceitems tbody tr").each(function() {
        $(this).change(function() {
            updateTotal();
        });
    });
});

function updateTotal() {

    //Calculate Subtotal for each item
    var quantity = $('.quantity').val();
    var price = $('.price').val();
    var subtotal = parseInt(quantity) * parseFloat(price);
    $('.subtotal').text(subtotal);
    //Calculate Grand Total
    var sum = 0;
    $('.linetotal').each(function() {
        sum += parseFloat($(this).text());
    });
    $('#grandTotal').html(parseFloat(sum));
}​

Found this code on here but I really don't have a clue and can't get it to work!

Some direction/help would be greatly appreciated!

Thanks very much Jase

Was it helpful?

Solution

Looks like you are a complete novice to jQuery.. !! Good start though.. Not hard to pick it up..

Here .price , .quantity and .lineTotal corresponds to class names of the columns they are talking about.. grandTotal is the id of the Total in the table..

I have put up a Working Example Updated for the case you are trying to work into.. Should be a good start..

But do take care that I have not added any conditions to check if the user input is valid or not... Try adding those while rolling it out.. Let me know if you face any difficulty in decoding it.

OTHER TIPS

Given this simple HTML as an example:

<table>
<tr>
<td>
<input type="text" name="unitCost[]" id="unitCost_1" value="15.99" class="editable"/>
</td>
<td>
<input type="text" name="quantity[]" id="quantity_1" value="1" class="editable"/>
</td>
</tr>
<tr>
<td>
<input type="text" name="unitCost[]" id="unitCost_2" value="2.50" class="editable"/>
</td>
<td>
<input type="text" name="quantity[]" id="quantity_2" value="1" class="editable"/>
</td>
</tr>
</table>

I think you'll want to change your jQuery to look something like this:

$(document).ready(function() {
    updateTotal();

    $(".editable").live("change", function() {
        updateTotal();
    });
});

Without seeing your actual HTML, it's hard to say whether or not there is anything wrong with you updateTotal() function

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top