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>
I just use
Number()
:You are missing the type conversion during the addition step...
var x = y + z;
should bevar x = parseInt(y) + parseInt(z);
if we have two input fields then get the values from input fields then add them using javascript.
Here goes your Code by parsing the variables in the function.
Answer
Use parseInt(...) but make sure you specify a radix value; otherwise you will run into several bugs (if the string begins with "0", the radix is octal/8 etc.).
Hope this helps!