2012-10-08 55 views
-4

在訂單中,每行有3個字段:數量,價格,總數。計算值

如何創建一個函數,在更改小數時計算小計,總計也是如此?

任何人都可以提出一種方法嗎?

+0

你有什麼嘗試或你會怎麼做呢?從那裏ppl更容易引導你 –

+0

http://knockoutjs.com/ –

回答

0

您需要爲每行添加一個偵聽器,以便在更新價格或數量時,可以獲取新數量和價格並更新總列。

在jQuery中,是這樣的:

$('.row').on('change', function() { 
    var quantity = $('.quantity', this).val(), // get the new quatity 
     price = $('.price', this).val(), // get the new price 
     total = price*quantity; 
    $('.total', this).val(total); //set the row total 

    var totals = $.map($('.row .total'), function(tot) { 
     return tot.val(); // get each row total into an array 
    }).reduce(function(p,c){return p+c},0); // sum them 
    $('#total').val(totals); // set the complete total 
}); 

這假設每個訂單行容器具有類row,每個數量具有類quantity,每行總具有類total和訂單總有編號爲total