-3

So i'm quite new to javascript and im trying to make this thing where i enter 2 values and it will either plus, multiply, divide etc. from what i enter in the code. But somehow when i try to multiply 5*2 it will show 10 but when i try 5+2 it will show 52, how do i fix this? I tried parseInt() but it didnt work

[Output][1]

Code:

function myfunction() {
var x = document.getElementById("fname").value;
var y = document.getElementById("lname").value;
var z = x + y;

document.getElementById("output").innerHTML = z;
<form>
<input type="Number" id="fname" value="" ><br><br>
<input type="number" id="lname" value="" ><br><br>


</form>

<button type="button" onclick="myfunction()">submit</button>

<p id="output"></p>
Philip
  • 3
  • 4
  • I found this article really helpful https://medium.freecodecamp.org/js-type-coercion-explained-27ba3d9a2839 – atiq1589 Apr 03 '18 at 07:36

2 Answers2

1

Cast the values to Numbers first. The .value from an element will always be a string.

function myfunction() {
var x = Number(document.getElementById("fname").value);
var y = Number(document.getElementById("lname").value);
var z = x + y;

document.getElementById("output").innerHTML = z;
}
<form>
<input type="Number" id="fname" value="" ><br><br>
<input type="number" id="lname" value="" ><br><br>


</form>

<button type="button" onclick="myfunction()">submit</button>

<p id="output"></p>
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

This is because both x & y is string.Use parseInt to convert the string to number before doing mathematical operation

function myfunction() {
  var x = document.getElementById("fname").value;
  var y = document.getElementById("lname").value;
  console.log(typeof x) // string
  var z = parseInt(x, 10) + parseInt(y, 10);

  document.getElementById("output").innerHTML = z;

}
<form>
  <input type="Number" id="fname" value=""><br><br>
  <input type="number" id="lname" value=""><br><br>


</form>

<button type="button" onclick="myfunction()">submit</button>

<p id="output"></p>
brk
  • 48,835
  • 10
  • 56
  • 78