how to ignore values that make totals become NaN in JavaScript

timbo007
timbo007 used Ask the Experts™
on
I have this Jquery code:
(there is more to it obviously but this is the part I need help with)

	total_entries=
	parseInt($("#beef_number_of_entries").val()) +
	parseInt($("#pork_number_of_entries").val()) +
	parseInt($("#saveloy_polony_cocktail_number_of_entries").val()) +
	parseInt($("#pre_cooked_barbecue_number_of_entries").val()) +
	parseInt($("#flavoured_pre_cooked_barbecue_number_of_entries").val()) +
	parseInt($("#flavoured_number_of_entries").val()) +
	parseInt($("#traditional_number_of_entries").val()) +
	parseInt($("#frankfurters_and_rounds_number_of_entries").val()) +
	parseInt($("#international_bratwurst_and_boerwors_number_of_entries").val()) +
	parseInt($("#international_mild_number_of_entries").val()) +
	parseInt($("#international_spicy_number_of_entries").val()) +
	parseInt($("#gourmet_number_of_entries").val());

alert('Total: ' + total_entries);

Open in new window


Now each of those #.. is a form input item.
If I have a field blank or not a number it produces NaN as the total.
I'd like to know how to only total each field if it's a number.

Thanks!!!
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Multitechnician
Top Expert 2014
Commented:
Using :
function parseInt2(n) {
   return (isNaN(parseInt(n)))?0:parseInt(n);
   //return (/\D/.test(n))?0:parseInt(n);
}

Open in new window


So :
	total_entries=
	parseInt2($("#beef_number_of_entries").val()) +
	parseInt2($("#pork_number_of_entries").val()) +
	parseInt2($("#saveloy_polony_cocktail_number_of_entries").val()) +
	parseInt2($("#pre_cooked_barbecue_number_of_entries").val()) +
	parseInt2($("#flavoured_pre_cooked_barbecue_number_of_entries").val()) +
	parseInt2($("#flavoured_number_of_entries").val()) +
	parseInt2($("#traditional_number_of_entries").val()) +
	parseInt2($("#frankfurters_and_rounds_number_of_entries").val()) +
	parseInt2($("#international_bratwurst_and_boerwors_number_of_entries").val()) +
	parseInt2($("#international_mild_number_of_entries").val()) +
	parseInt2($("#international_spicy_number_of_entries").val()) +
	parseInt2($("#gourmet_number_of_entries").val());

alert('Total: ' + total_entries);

Open in new window

Author

Commented:
Thanks, works a charm!!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial