0

I'm new at Javascript coding and I'm trying to make my first calculator: it has three text boxes where users type the first number they want to add on the first text box, and the second number on the second text box, and then they click on a button and the result of the adding of these two numbers appears on the third text box. But when I do 1 + 1 it results 11 instead of 2 and when I do 2 + 2 it results 22 instead of 4. I know that this is a very newbie question but can you guys please help me? What am I doing wrong? Also sorry for my bad english, I'm brazilian. Here is the JS code:

<script>
  function AddResolve() {
    document.getElementById('AddResult').value = document.getElementById('AddInputOne').value + document.getElementById('AddInputTwo').value
  }
</script>

And here is the HTML code of the three boxes and the button:

<input type="text" id="AddResult">
<input type="text" id="AddInputOne">
<input type="text" id="AddInputTwo">
<input type="button" id="AddButton" onclick="AddResolve()">
savanto
  • 4,470
  • 23
  • 40

3 Answers3

8

It’s because field values in Javascript are strings, not numbers. You need to force them to be integers:

document.getElementById('AddResult').value =
  parseInt(document.getElementById('AddInputOne').value) +
  parseInt(document.getElementById('AddInputTwo').value)

Calling parseInt() with the value of the field will convert the string to an integer.

Buck Doyle
  • 6,333
  • 1
  • 22
  • 35
0

The value stored in a text box is a string, and JavaScript adds strings by concatenating them. You need to convert both strings to numbers with parseInt(value, 10).

Eevee
  • 47,412
  • 11
  • 95
  • 127
0

just a guess, is there any chance you are adding "2" + "2" or "2" + 2? Adding strings is not adding numbers.

make it ~~"2" or parseInt("2") depending on result you need

reference:

0) JavaScript string and number conversion

1) What is the "double tilde" (~~) operator in JavaScript?

2) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt

Community
  • 1
  • 1
mmln
  • 2,104
  • 3
  • 24
  • 33