I am adding two numbers, I get a correct value.
Got the value after sum
function myFunction() {
var y = document.getElementById("txt1").value;
var z = document.getElementById("txt2").value;
var x = Number(y) + Number(z);
document.getElementById("demo").innerHTML = x;
}
<p>
Click the button to calculate x.
<button onclick="myFunction()">Try it</button>
</p>
<p>
Enter first number:
<input type="text" id="txt1" name="text1" value="1">
Enter second number:
<input type="text" id="txt2" name="text2" value="2">
</p>
<p id="demo"></p>
Hey Friends Its Very Simple
This is an old question, but 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 like3+'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 getNaN
, 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()
orparseFloat()
, 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. Where they fail is 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:
If you’re prepared to coalesce an invalid string to 0, you can use:
This won't sum up the number, instead it will concatenate it:
What you need to do is:
You must use parseInt in order to specify the operation on numbers. Ex:
An alternative solution, just sharing :) :
You can also write : var z = x - -y ; And you get correct answer.