-3

I am trying to add numbers on text input using javascript, but instead of 4+2=6, It shows: 4+2=42

My code:

    <input type="number" id="number1"> <br>
<button onclick="sayHello();">HI</button>
<p id="texthere"></p>

<script>
function sayHello() {
let n1 = document.getElementById("number1").value;
document.getElementById("texthere").innerHTML = n1 + 2;
}
</script>

Thank you.

Michel
  • 7
  • 1
    Because n1 type is `string` and not `int`. `parseInt(n1)` solves this. – silentw Nov 26 '21 at 15:20
  • 1
    because you are dealing with strings, not numbers. You are concatenating `"4" + "2"` and are not adding `4+2`. You have to convert your strings to numbers. – Thomas Nov 26 '21 at 15:21
  • Don’t use `parseInt`. Use the available APIs properly: `document.getElementById("texthere").textContent = document.getElementById("number1").valueAsNumber + 2;`. – Sebastian Simon Nov 26 '21 at 15:28
  • Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Nov 26 '21 at 15:29

3 Answers3

0

You should do parseInt

document.getElementById("texthere").innerHTML = parseInt(n1,10) + 2;
Beso
  • 1,176
  • 5
  • 12
  • 26
  • 1
    Please use `parseInt` [_with_ the second parameter, `10`](/q/16880327/4642212). Consider using [`Number`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Number#Function_syntax) or [`parseFloat`](//developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) instead, or, specifically for ``s, [`.valueAsNumber`](//developer.mozilla.org/docs/Web/API/HTMLInputElement#Properties). – Sebastian Simon Nov 26 '21 at 15:27
0

The value of a text input is a string by default, so you’re doing ‘4’ + ‘2’ = ‘42’ in the same way ‘abc’ + ‘def’ = ‘abcdef’. You can call parseInt on the values to get integers.

Sudhir Jonathan
  • 16,998
  • 13
  • 66
  • 90
0

document.getElementById("number1").value returns a string. That is why it is concatenating 4 with 2 instead of adding them. Try converting it to a number before passing it to document.getElementById("texthere").innerHTML . parseInt() function is used to do this conversion.