-2

In this script i am passing number values but i get them as concatenated values.Why is javascript behaving so.I use a function named add and passing two number parameters.Why is it considered as string.I am using chrome browser

  <input type="number" id="num1"/>
  <input type="number" id="num2"/>
   <button onclick='alert(add(document.getElementById("num1").value,document.getElementById("num2").value))' >sum</button>  

<script>
    const add=function( num1, num2){
        return num1+num2;
    }
    </script>
  
Midhun Raj
  • 925
  • 2
  • 7
  • 21

3 Answers3

1

Because you get the values from an Input-field and this is allways from type string. So you had to use parseInt to get an Integer.

    const add=function( num1, num2){
        return parseInt(num1)+parseInt(num2);
    }
<input type="number" id="num1"/>
<input type="number" id="num2"/>
<button onclick='alert(add(document.getElementById("num1").value,document.getElementById("num2").value))' >sum</button>  
Vladimir Djuricic
  • 4,323
  • 1
  • 21
  • 22
Sascha
  • 4,576
  • 3
  • 13
  • 34
1

You need to parse values to int.

ShortHand for Int parsing is + operator or simple parseInt(<stringNumber>).

const add = function( num1, num2){
   return +num1 + +num2;
}
<input type="number" id="num1"/>
<input type="number" id="num2"/>
<button onclick='alert(add(document.getElementById("num1").value,document.getElementById("num2").value))' >sum</button>  
 
Ajeet Eppakayala
  • 1,186
  • 1
  • 10
  • 17
1

You should avoid inline javascript and place javascript code in external js file. For better readability, debug and testing purposes.

From @Sascha answer you should convert input text to number and then do the calculations using parseInt. Also, check @Ajeet_Eppakayala answer as an alternative solution.

let submBtn = document.getElementById('sbtBtn');
     
    function calculate(e){
            
            e.preventDefault();
            let num1El = document.getElementById('num1');
            let num2El = document.getElementById('num2');
            
            let res = document.getElementById('result');
            
            let num1 = parseInt(num1El.value);
            let num2 = parseInt(num2El.value);
            
            if (Number.isInteger(num1) && Number.isInteger(num2)){
                res.innerHTML = add(num1,num2);
            }else{
               res.innerHTML = "Please enter numbers";
               num1El.focus();
            }
            
    }
        
        const add = (num1,num2) => {
             return parseInt(num1) + parseInt(num2);
        }

    submBtn.addEventListener('click',calculate);
<form>
        <input type="text" id="num1" />
        <input type="text" id="num2" />
        <input type="submit" id="sbtBtn" value="Sum" />
        <p id="result"><p>
    </form>
Marios Nikolaou
  • 1,326
  • 1
  • 13
  • 24