Tuesday, 15 March 2011

jquery: Adding numbers and concatenation

This one stumbled me for a bit. I kept trying to calculate the total of 5 input fields using jquery/javascript. But the numbers kept concatenating.

Turns out that if any of the input fields don't have a value, then it becomes a string and so the whole value becomes a string.

A little trick to get around this is to simply - zero which will convert it to a number without affecting the result.


var tot = ($('#MarginVatForm_purchaseCost1').val() - 0) + ($('#MarginVatForm_purchaseCost2').val() - 0) + ($('#MarginVatForm_purchaseCost3').val() -0) + ($('#MarginVatForm_purchaseCost4').val() - 0) + ($('#MarginVatForm_purchaseCost5').val() - 0);

This is only for the + operator because it doubles as string concatenation. Other arithmetic operators seem fine.

No comments:

Post a Comment