Why does this give me a String every time?

I received input input tags, but no matter what I write in the inputs, it recognizes the value of the string, so I cannot use my conditions.

and the second problem, if I type "ddd" for the first input and "111" for the second input and press the button, it shows NaN on the console. I want to show a warning instead. How can I fix them?

function addFunc() {
  var x = document.getElementById("num1").value;
  var y = document.getElementById("num2").value;

  if (typeof x == 'string' || typeof y == 'string') {
    var result = parseInt(x) + parseInt(y);
    console.log(result);
  } else {
    alert("Wrong Entry!");
  }
}
<input id="num1">
<input id="num2">
<button type="button" onclick="addFunc()">ADD</button>
<p id="result"></p>
Run code
+4
source share
2 answers

The value of the input field will always be a string. Try using isNaN()to determine if the decimal is parsed correctly:

function addFunc() {
    var x = parseInt(document.getElementById("num1").value);
    var y = parseInt(document.getElementById("num2").value);

    if ( !isNaN(x) && !isNaN(y) )
    {
        var result = x + y;
        console.log(result);
    }

    else {
        alert("Wrong Entry!");
    }
}
<form onsubmit="addFunc(); return false">
  <input type="text" id="num1" />
  <input type="text" id="num2" />
  <input type="submit" value="Add" />
</form>
Run code

, (1 ), + . , NaN:

function addFunc() {
    var x = +document.getElementById("num1").value;
    var y = +document.getElementById("num2").value;

    if ( !isNaN(x) && !isNaN(y) )
    {
        var result = x + y;
        console.log(result);
    }

    else {
        alert("Wrong Entry!");
    }
}
<form onsubmit="addFunc(); return false">
  <input type="text" id="num1" />
  <input type="text" id="num2" />
  <input type="submit" value="Add" />
</form>
+5

parseInt NaN, char ( ) :

parseInt("x89"); // NaN
parseInt("89x"); // 89
parseInt("89.34ed"); // 89
parseInt("-89.34ed"); // -89
parseInt("x-89.34ed"); // NaN

( ), isNaN().

0

Source: https://habr.com/ru/post/1651560/


All Articles