我需要使用Javascript添加和减去。我已成功将所有输入字段添加到一起,但无法从第一个字段中减去该总数。我在下面插入了一个例子,而你的余额为1500,然后插入让我们说你有3个字段的业务成本。如上所述,我可以成功地添加所有字段,但不能从余额中减去总金额并将其显示在下方。
添加脚本
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('input').each(function() {
$(this).keyup(function(){
calculateTotal($(this));
});
});
});
function calculateTotal(src) {
var sum = 0;
var sumtable = src.closest('.sumtable');
sumtable.find('input').each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
sumtable.find(".total").html(sum.toFixed(2));
}
</script>
HTML
<tr>
<td>
<font face='Verdana'>
<input name='amount' size='6' value='1500.00'></font></td>
</tr>
<table border='0' cellpadding='0' cellspacing='0' width='16%' height='31' class='sumtable'>
<tr>
<font face='Verdana' style='font-size: 8pt; font-weight:700'>
Amount:</font></td>
</tr>
<tr>
<td>
<font face='Verdana'>
<input name='amount' size='6' ></font></td>
</tr>
<tr>
<td>
<font face='Verdana'>
<input name='amount' size='6' ></font></td>
</tr>
<tr>
<td>
<font face='Verdana'>
<input name='select3_amount' size='6' ></font></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td>
<p align='right'><b>
<font face='Verdana' size='2'>Total Cost: $
</font></b> </td>
<td><b><font face='Verdana' size='2'><span class='total'>0</span></font></b></td>
</tr>
<tr>
<td>
<p align='right'><b>
<font face='Verdana' size='2'>Total Remaining: $
</font></b> </td>
<td><b><font face='Verdana' size='2'><span class='balance'>0</span></font></b></td>
</tr>
</table>
我需要添加什么才能显示剩余余额?
答案 0 :(得分:1)
这是你的想法:http://jsfiddle.net/ZZX5D/?
var bal = $('input[name="amount"]').val();
bal = bal - sum
sumtable.find(".balance").html(bal.toFixed(2));
答案 1 :(得分:0)
您不是首先减去值。
$(function(){
$('input').each(function() {
$(this).keyup(function(){
calculateTotal($(this));
});
});
});
function calculateTotal(src) {
var sum = 0;
var sumtable = src.closest('.sumtable');
sumtable.find('input').each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
sumtable.find(".total").html(sum.toFixed(2));
var balance = parseFloat($('.actual').val()) - sum
sumtable.find(".balance").html(balance.toFixed(2));
}
Added a `class actual` to the **Actual Amount**
<强> Check fiddle 强>