-7

I have a problem in output. For example, 2+3 = 23 instead of 5.

function addition() {
  var v1 = document.getElementById("n1").value;
  var v2 = document.getElementById("n2").value;

  document.getElementById("demo").innerHTML = v1 + v2;
}
Oladipo
  • 1,579
  • 3
  • 17
  • 33
Khaled
  • 1
  • 1
  • 2
    Make the values *numbers*. – jonrsharpe Dec 23 '19 at 17:23
  • var v1=parseInt(document.getElementById("n1").value); var v2=parseInt(document.getElementById("n2").value); document.getElementById("demo").innerHTML = v1+v2; – Tinu Jos K Dec 23 '19 at 17:24
  • `v1` and `v2` are both strings. Adding strings concatenates them. –  Dec 23 '19 at 17:24
  • 1
    You need to learn JavaScript basics, have a look at [assignment operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators). – soywod Dec 23 '19 at 17:25

1 Answers1

0

v1 and v2 are strings, which means adding them concatenates them.

Instead, turn v1 and v2` into numbers.

function addition() {
  var v1=document.getElementById("n1").value;
  var v2=document.getElementById("n2").value;

  document.getElementById("demo").innerHTML = Number(v1) + Number(v2);
}
<input id = "n1" value = "2">
<input id = "n2" value = "3"><br>
<button onCLick = "addition()">Add Numbers</button>
<p id = "demo"></p>

You can also use parseInt() or parseFloat() instead of Number() if they don't have to be strictly numbers.

Yousername
  • 1,012
  • 5
  • 15