-1

when i'm using the function to add two numbers together it appears next to each other like (2+2=22) although it works well with other mathematical operators (* and /)

    <html>
  <head>
    
        <title>Adding</title>
    
    
  </head>

  <body>
      
      <input type="number" id="one">
      <input type="number" id="two">
      <button id="press">seed</button>
    
    <script type="text/javascript">
        
        function adding (a, b){
                return (a + b);
                }
        document.getElementById("press").onclick = function(){
            var first = document.getElementById("one").value;
            var second = document.getElementById("two").value;
                
            alert(adding(first, second));
        }
        
    </script>
    
  </body>
K. Kassed
  • 17
  • 3
  • 1
    Does this answer your question? [Adding two numbers concatenates them instead of calculating the sum](https://stackoverflow.com/questions/14496531/adding-two-numbers-concatenates-them-instead-of-calculating-the-sum) – devlin carnate Aug 13 '20 at 21:55
  • Does this answer your question? [How to force JS to do math instead of putting two strings together](https://stackoverflow.com/questions/4841373/how-to-force-js-to-do-math-instead-of-putting-two-strings-together) – Sebastian Simon Aug 15 '20 at 03:14

3 Answers3

4

You are adding the string "2" plus "2" hence they are just appended. You will need to typecast into a number first.

console.log(parseInt("2")+Number("2"))
MarkCBall
  • 229
  • 1
  • 4
1

The value attribute returns a string, for which the + operator is defined to concatenate. You can use the unary plus operator to simply convert them to a numbers.

function adding(a, b) {
  return (a + b);
}
document.getElementById("press").onclick = function() {
  var first = +document.getElementById("one").value;
  var second = +document.getElementById("two").value;

  alert(adding(first, second));
}
<input type="number" id="one">
<input type="number" id="two">
<button id="press">seed</button>
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
0

You can only write parseint where you return.

 function adding (a, b){
    return (parseInt(a) + parseInt(b));
}
document.getElementById("press").onclick = function(){
    var first = document.getElementById("one").value;
    var second = document.getElementById("two").value;

    alert(adding(first, second));
}
<input type="number" id="one">
<input type="number" id="two">
<button id="press">seed</button>
Kaan Demir
  • 442
  • 2
  • 9