2010-08-17 98 views
2

我想知道是否有人可以幫助我。jQuery添加多個文本框

我有一個網頁,其中有一些文本框(動態數量,可能是3,可能是30),每個用戶可以輸入一個數字,我有一個總數在底部。

目前我有這樣的:

$('input.qty').change(function() { 
// Get the current total value 
var total = $('#total'); 
// Update it with the changed input's value 
total.val(parseInt(total.val()) + parseInt($(this).val())); 
}); 

示例HTML:

​​

它增加了細第一次,但是當你開始改變的值,簡單地將新的金額佔總而不是把所有的盒子加起來。

我該如何分類?也許使用每個attr?

回答

2

您可以通過所有這些循環使用.each(),總結起來,就像這樣:

$('input.qty').change(function() { 
    var sum = 0; 
    $('input.qty').each(function() { sum += parseInt(this.value, 10); }); 
    $('#total').val(sum); 
}); 

You can give it a try here,如果你想讓它calc下每個按鍵然後使用.keyup()代替.change()like this