计算价值

时间:2012-10-08 17:31:31

标签: javascript calculated-field

在订单表格中,每行有3个字段:数量,价格,总数。

如何创建一个函数,在更改数字时,计算小计的总数?

有人可以建议吗?

1 个答案:

答案 0 :(得分: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类,订单总数有id total

相关问题