我有 3 个字段 Quantity、Rate、Total Amount。如果任何一个键入数量或费率字段,则金额将显示在总金额字段上。我还有一个添加按钮。如果有人单击添加按钮,则动态创建新行和删除链接。我的问题是如果我键入数量或比率字段,那么 calculateSum() 函数可以正常工作。假设我创建了 2 行,其总金额为 100+(100+100)=300。如果我删除第一个没有任何改变。如果我删除最后一个,则结果显示 200。但正确的结果是 100。请有人指出我在这里可能做错了什么?非常感谢。这是我的代码:
<html>
<head>
<title>Invoice</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on("keyup",".qty, .rate",function(){
calculateSum();
});
$(document).on("click",".del",function(){
calculateSum();
});
});
function calculateSum() {
var qty = [];
$(".qty").each(function() {
var num = parseFloat(this.value) || 1;
qty.push(num);
});
var rate = [];
$(".rate").each(function() {
var num = parseFloat(this.value) || 0;
rate.push(num);
});
var total = 0;
$('input[name="total_amount[]"]').each(function(i){
var amount = qty[i].toFixed(2)*rate[i].toFixed(2);
total += amount;
$(this).val(amount);
});
$("#sub_total").text(total);
}
</script>
<script type="text/javascript" language='javascript'>
/*
This script is identical to the above JavaScript function.
*/
var ct = 1;
function new_link()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// link to delete extended form elements
var delLink = '<div style="text-align:right;margin-top:-20px"><a class="del" href="javascript:delIt('+ ct +')">Delete</a></div>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// function to delete the newly added set of elements
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(ele);
}
</script>
<style type="text/css">
table
{
border: 1px solid black;
width: 600px;
}
td
{
border: 1px solid black;
padding:5px 5px 5px 5px;
}
</style>
</head>
<body>
<div id="newlink">
<table cellpadding="0" cellspacing="0">
<tr>
<td>Quantity</td>
<td>Rate</td>
<td>Total Amount</td>
</tr>
<tr>
<td><input class='qty' type='text' name='qty[]'/></td>
<td><input class='rate' type='text' name='rate[]'/></td>
<td><input class='total_amount' type='text' name='total_amount[]'/></td>
</tr>
</table>
</div>
<div id="sub_total">0</div>
<input type="button" value="Add" onclick="new_link()"/>
<div id="newlinktpl" style="display:none">
<table cellpadding="0" cellspacing="0">
<tr>
<td><input class='qty' type='text' name='qty[]'/></td>
<td><input class='rate' type='text' name='rate[]'/></td>
<td><input class='total_amount' type='text' name='total_amount[]'/></td>
</tr>
</table>
</div>
</body>
</html>