Javascript Calculation Returns Nan
Solution 1:
The code is using a combination of .each()
AND a for-in loop... and strangely the callback from a blur()
function? It can be simplified like this:
var amount = 0;
$('#bill_amount:disabled, #fine, #discount, #other_cost')
.blur()
.each(function() {
var sign = this.id === 'discount' ? -1 : 1;
amount += parseFloat($(this).val()) * sign;
});
$('#total').val(amount);
Update:
Oh, you want the total to update on blur... try this code:
var $values = $('#bill_amount:disabled, #fine, #discount, #other_cost');
$values.on('blur', function() {
var amount = 0;
$values.each(function(){
var sign = this.id === 'discount' ? -1 : 1;
amount += parseFloat($(this).val()) * sign;
});
$('#total').val(amount);
});
Solution 2:
I can see stuff like this all around:
var fine = +$('#fine');
The jQuery()
method returns jQuery
objects, not numbers or even strings. Forcing a number cast will thus return NaN
.
You need to first grab the text inside and than parse numbers of out it. How to do it depends on how your HTML is structured but in general:
- In form fields you can normally use
.val()
- In most other tags you can use
.text()
Solution 3:
Make sure that all values are interpreted as numbers by JavaScript. Otherwise it will try to calculate some odd result from a string, which might get interpreted as something else than the a decimal number (hex, octa, ...).
Solution 4:
You array holds numbers and you act like they are strings
var chargeAble = [ //this holds values
partial_cost,
fine,
discount,
other_cost
];
and in the loop you are using it for an id???
chargeAble[charge].attr('id')
Post a Comment for "Javascript Calculation Returns Nan"