I’m attempting to display a subtotal each time a customer enters a quantity. However, when I loop through my inputs, I get a NaN as the total. I believe it may be the way I’m declaring the subtotal variable in my script, but I haven’t come across this before:
$('.item-qty input').bind('keyup', function(){
var subtotal = 0.0;
$('.item-qty input').each(function(){
var class = $(this).attr('id');
var qty = $(this).val();
var price = $('.'+class).html();
price = parseFloat(price);
qty = parseInt(qty);
subtotal = subtotal + (price * qty);
});
$('.subtotal input').val(subtotal);
});
parseFloatandparseIntcan returnNaNif the first character of the string cannot be converted to a number.So, I would safeguard against it like this (
NaNis a falsy value):Arithmetic operations on numbers with the value
NaNalmost always result inNaN(NaN + 5will result inNaN.) That means, if only one of the input cannot be parsed byparseFloatorparseInt, your current code would end up calculatingNaNfor the subtotal.It’s already been mentioned in the comments (by Felix mostly) but I think it’s worth the emphasis as these are important concerns:
radixargument to theparseIntfunction;classfor variable names: It’s a reserved (not used, but reserved) keyword;