0
我已經創建了一個用戶可以添加行的表格。而就具體列,有一個輸入,其中用戶可以插入值和jQuery將總結所有的值,並將其插入到另一個輸入使用JQuery計算動態表中的每個輸入值
所以,要清楚,這裏有一個例子:
問題是,我添加更多的行後,它不會將所有輸入相加。它只會求和第一行的第一個輸入,但當我在第二,第三,第四和...輸入中插入一個值時,它不會求和。
這裏的表:
<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;
}
}
}
同去與輸入貨幣。它只適用於第一行的第一個輸入。
需要幫助
謝謝
謝謝! 現在接下來的問題是我使用jQuery .toFixed()將.amount輸入轉爲十進制數,但是它僅適用於第一行 –
@SyafiqAZ我不確定你會得到什麼...... – entropic
對不起,不足以解釋清楚。我已更新了我的問題。希望是明確的 –