0

I have a problem.

I want to show an alert saying "you have a problem" when the user enters something into the input that is not a number.

function function1() {
  var x = document.getElementById("number1").value;
  if (Number.isNaN(x)) {
    alert("you have a problem");
  }

}
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Mohsen Yeganeh</title>
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <input type="text" id="number1">
  <button type="submit" onclick="function1()">click me</button>


</body>

</html>

It is not working, however. Where is it going wrong?

Spectric
  • 30,714
  • 6
  • 20
  • 43

1 Answers1

0

Number.isNaN() checks whether the argument is NaN, not whether or not it is a number.

Number.isNaN(NaN) // true
Number.isNaN("Hello World!") // false, "Hello World!" != NaN

You should be using isNaN() instead, which checks whether the argument is a number or not:

function function1() {
  var x = document.getElementById("number1").value;
  if (isNaN(x)) {
    alert("you have a problem");
  }
}
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Mohsen Yeganeh</title>
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <input type="text" id="number1">
  <button type="submit" onclick="function1()">click me</button>


</body>

</html>
Spectric
  • 30,714
  • 6
  • 20
  • 43