2016-06-11 45 views
0

所以我有问题,我的输入值只有当我点击输入字段(“总”输入字段,下面的“Suma”(“Kiekis”*“Kaina”=“Suma”)列和哪些是只读)更新时,但我想自动更新“总计”字段(位于“Bendra suma”底部附近)。如何在不点击输入栏的情况下更新输入值?

JS代码:

$(document).on('keyup change', '.quantity, .price', function() { 
    var row = $(this).closest('tr').get(0); 
    var rowPrice = $(row).find('.price').val(); 
    var rowQuantity = $(row).find('.quantity').val(); 

    $(row).find('.total').val((rowPrice * rowQuantity).toFixed(2)); 

    $('.total').blur(function() { 
     var sum = 0; 

     $('.total').each(function() { 
      sum += parseFloat($(this).val()); 
     }); 

     $('#totals').val((sum).toFixed(2)); 
    }); 

}); 

您可以测试它是如何工作的jsfiddle:

https://jsfiddle.net/xqy6qafk/

预先感谢帮助!

回答

0

你并不需要把代码中的模糊事件处理程序...

放入KEYUP/change事件处理部分。 ..

卸下8号线

$(document).on('keyup', '.quantity, .price', function() { 

和倒数第二行...

}); 

所以你有一些看起来像这样...

$(document).on('keyup change', '.quantity, .price', function() { 
    var row = $(this).closest('tr').get(0); 
    var rowPrice = $(row).find('.price').val(); 
    var rowQuantity = $(row).find('.quantity').val(); 

    $(row).find('.total').val((rowPrice * rowQuantity).toFixed(2)); 

    var sum = 0; 

    $('.total').each(function() { 
     sum += parseFloat($(this).val()) || 0; // If a string is entered, use 0 instead. 
    }); 

    $('#totals').val((sum).toFixed(2)); 

}); 
1

删除变化所以它会激活KEYUP

$(document).on('keyup', '.quantity, .price', function() { 
+0

尝试。没有帮助 – Sprunkas

+0

https://jsfiddle.net/xqy6qafk/1/我只是改变凯纳场,总和自动更新 – misha130

+0

Upvoted你的答案...但它缺少关闭此声明的代码。 – shramee

1

此更新汇总。

$(document).on('keyup change', '.quantity, .price', function() { 
    var row = $(this).closest('tr').get(0); 
    var rowPrice = $(row).find('.price').val(); 
    var rowQuantity = $(row).find('.quantity').val(); 

    $(row).find('.total').val((rowPrice * rowQuantity).toFixed(2)); 

    // Get all the totals from each row and convert them to 
    // an array of floats. Then sum them together with reduce 
    var totalPrice = $('.total').map(function (index, el) { 
     return parseFloat($(el).val()) || 0; 
    }).get().reduce(function (a,b) { return a + b }, 0) 

    // Update the total field with the calculated totals 
    $('#totals').val(totalPrice) 
}); 

https://jsfiddle.net/xqy6qafk/2/

+0

感谢您编辑我的答案wot,Upvoted你的答案,并接受你的编辑:) – shramee

相关问题