2014-07-10 50 views
0

我已經創建了一個用戶可以添加行的表格。而就具體列,有一個輸入,其中用戶可以插入值和jQuery將總結所有的值,並將其插入到另一個輸入使用JQuery計算動態表中的每個輸入值

所以,要清楚,這裏有一個例子:

example

問題是,我添加更多的行後,它不會將所有輸入相加。它只會求和第一行的第一個輸入,但當我在第二,第三,第四和...輸入中插入一個值時,它不會求和。

這裏的表:

<table id="twe"> 
     <thead> 
     <tr> 
      <th valign="middle"><center>Amaun</center></th> 
     </tr> 
     </thead> 
     <tbody> 
     <tr> 
      <td><input name="amount[]" type="text" class="amount" id="amount[]" value="" /></td> 
     </tr> 
     </tbody> 
     </table> 

<button type="button" onclick="addrow('twe')" title="Add">Add</button> 
<br/> 
<br/> 
Sum: <input type="text" id="sum" /> 

而這裏的腳本

(function($) { 
    $.fn.currencyFormat = function() { 
     this.each(function(i) { 
      $(this).change(function(e){ 
       if(isNaN(parseFloat(this.value))) return; 
       this.value = parseFloat(this.value).toFixed(2); 
      }); 
     }); 
     return this; //for chaining 
    } 
})(jQuery); 

$(document).ready(function() { 
    $('.amount').currencyFormat(); 

}); 


$(document).ready(function() { 
$(".amount").each(function() { 

    $(this).keyup(function() { 
     calculateSum(); 
    }); 
}); 

}); 

function calculateSum() { 

var sum = 0; 
$(".amount").each(function() { 

    if (!isNaN(this.value) && this.value.length != 0) { 
     sum += parseFloat(this.value); 
    } 

}); 
$("#sum").val(sum.toFixed(2)); 
} 


function addrow(tableID) { 

     var table = document.getElementById(tableID); 

     var rowCount = table.rows.length; 
     var row = table.insertRow(rowCount); 

     var colCount = table.rows[1].cells.length; 

     for(var i=0; i<colCount; i++) { 

      var newcell = row.insertCell(i); 

      newcell.innerHTML = table.rows[1].cells[i].innerHTML; 
      switch(newcell.childNodes[0].type) { 
       case "text": 
         newcell.childNodes[0].value = ""; 
         break; 

      } 
     } 
} 

同去與輸入貨幣。它只適用於第一行的第一個輸入。

需要幫助

謝謝

回答

1

的問題在於,當你要綁定的事件。在您的document.ready函數中,您正在通過.amount項目循環並綁定一個鍵值,但這不會計算將創建的FUTURE項目。你想要做的是綁定所有實例和將來的實例來運行計算。

這可以使用jQuery中的.on事件來完成。你document.ready將作如下更新:

$(document).ready(function() { 
    $(document).on("keyup", ".amount", calculateSum); 
}); 

工作小提琴http://jsfiddle.net/p2Hbm/

+0

謝謝! 現在接下來的問題是我使用jQuery .toFixed()將.amount輸入轉爲十進制數,但是它僅適用於第一行 –

+0

@SyafiqAZ我不確定你會得到什麼...... – entropic

+0

對不起,不足以解釋清楚。我已更新了我的問題。希望是明確的 –