troggy69 troggy69 - 3 months ago 12
jQuery Question

Remove NaN from the total field while function is adding the two inputs together

I am adding two fields together to get the total but when i type into the first field the total field shows NaN which i need it not to. I have tried 5 different options to resolve this issue but none seem to remove NaN while the function runs.

$j(function() {

var new_fees = 0.00;
var referral_fees = 0.00;

$j('#new_fees').keyup(function() {
updateTotal();
});

$j('#referral_fees').keyup(function() {
updateTotal();
});

var net_fees=parseFloat($j('#net_fees').val());
if(isNaN(net_fees)){
net_fees=0;
}

var updateTotal = function () {
new_fees = parseFloat($j('#new_fees').val());
referral_fees = parseFloat($j('#referral_fees').val());
$j('#net_fees').val(new_fees + referral_fees);

var output_total = $j('#net_fees');
var total = new_fees + referral_fees;

output_total.val(total);
};
});


Here is the fiddle link but it doesn't seem to work at all in fiddle where as it does on my page

Answer

I updated your "updateTotal" method, please try it.

var updateTotal = function () {
     new_fees = parseFloat($('#new_fees').val());
     referral_fees = parseFloat($('#referral_fees').val());
     $('#net_fees').val(new_fees + referral_fees);
     var output_total = $('#net_fees');
     var total = new_fees + referral_fees;
     if(isNaN(total)){
         total=0;
     }
     output_total.val(total);
};

try https://jsfiddle.net/ydLtcrya/1/

Comments