jquery table rows line totals and grand total

限于喜欢 提交于 2019-12-02 09:36:04

问题


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!

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


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/12324928/jquery-table-rows-line-totals-and-grand-total

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!