0

I am trying to make a very simple adding calculator but it seems to be concatenating them instead of adding the values, can someone help me?

window.onload = function(){
  document.getElementById("addingButton").addEventListener("click", add);

function add(e){    
    var x = document.getElementById("inputOne").value;
    
    var y = document.getElementById("inputTwo").value;
    
    var out = "";
     
    out += "Output: " + (x + y);
    
    alert(out);
  }
}
 <div id="container">
      <button id="addingButton"> Add!</button>
         <input id="inputOne" type=number/>
         <input type=number id="inputTwo"/>
   </div>
Makwana Prahlad
  • 1,025
  • 5
  • 20
  • [Duplicate](https://google.com/search?q=site%3Astackoverflow.com+js+input+value+as+number) of [Input value is a string instead of a number](https://stackoverflow.com/q/27849944/4642212). – Sebastian Simon Feb 05 '21 at 04:01

2 Answers2

3

You'll need to parse the values individually using the parseInt() function like so:

window.onload = function() {
  document.getElementById("addingButton").addEventListener("click", add);
  function add(e) {
    var x = document.getElementById("inputOne").value;
    var y = document.getElementById("inputTwo").value;
    var out = "";
    out += "Output: " + (parseInt(x) + parseInt(y));
    alert(out);
  }
}
<div id="container">
  <button id="addingButton"> Add!</button>
  <input id="inputOne" type=number/>
  <input type=number id="inputTwo" />
</div>
Spectric
  • 30,714
  • 6
  • 20
  • 43
  • 1
    Note to those reading this: `parseInt('123foo bar')` returns `123`. If you don't like this, use `Number()` instead. – 0xLogN Feb 05 '21 at 03:55
  • Please use `parseInt` [with the second parameter `10`](https://stackoverflow.com/q/16880327/4642212). Consider using [`Number`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number#Function_syntax) or [`parseFloat`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) instead, or, specifically for ``s, [`.valueAsNumber`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement#Properties). – Sebastian Simon Feb 05 '21 at 04:03
0

This will work. You can remove 'type='number'' if you like.

window.onload = function(){
  document.getElementById("addingButton").addEventListener("click", add);

function add(e){    
    var x = parseInt(document.getElementById("inputOne").value);
    
    var y = parseInt(document.getElementById("inputTwo").value);
    
    var out = x+y;
     
    
    
    alert("Output: " + out);
  }
}
<div id="container">
      <button id="addingButton"> Add!</button>
         <input type='number' id="inputOne"/>
         <input type='number' id="inputTwo"/>
   </div>