The following may be useful in general terms.
First, HTML form fields are limited to text. That applies especially to text boxes, even if you have taken pains to ensure that the value looks like a number.
Second, JavaScript, for better or worse, has overloaded the +
operator with two meanings: it adds numbers, and it concatenates strings. It has a preference for concatenation, so even an expression like 3+'4'
will be treated as concatenation.
Third, JavaScript will attempt to change types dynamically if it can, and if it needs to. For example '2'*'3'
will change both types to numbers, since you can’t multiply strings. If one of them is incompatible, you will get NaN
, Not a Number.
Your problem occurs because the data coming from the form is regarded as a string, and the +
will therefore concatenate rather than add.
When reading supposedly numeric data from a form, you should always push it through parseInt()
or parseFloat()
, depending on whether you want an integer or a decimal.
Note that neither function truly converts a string to a number. Instead, it will parse the string from left to right until it gets to an invalid numeric character or to the end and convert what has been accepted. In the case of parseFloat
, that includes one decimal point, but not two.
Anything after the valid number is simply ignored. They both fail if the string doesn’t even start off as a number. Then you will get NaN
.
A good general purpose technique for numbers from forms is something like this:
var data=parseInt(form.elements['data'].value); // or parseFloat
If you’re prepared to coalesce an invalid string to 0, you can use:
var data=parseInt(form.elements['data'].value) || 0;
<input type="number">
, you can simply get its.valueAsNumber
property directly.