Reputation: 59
I need to add and subtract using Javascript. I've been successful at adding all the input fields together, but been unable to subtract that total amount from the first field. I've inserted an example below whereas you would start out with a balance of 1500, then insert in let's say cost of business in which you have 3 fields to do so. As mentioned I can successfully add up all fields, but can't subtract that total amount from the balance and display it right underneath.
Adding Script
<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>
What do I need to add to display the Remaining Balance?
Upvotes: 1
Views: 8727
Reputation: 55740
You are not subtracting the values in the first place.
$(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**
Upvotes: 0
Reputation: 5069
Is this what you have in mind: http://jsfiddle.net/ZZX5D/ ?
var bal = $('input[name="amount"]').val();
bal = bal - sum
sumtable.find(".balance").html(bal.toFixed(2));
Upvotes: 1