2016-06-11 75 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

相關問題