Search code examples
javascriptnumbers

How to check if user input is a number?


I would like to check if user input is a number; the 'input' is from an html input tag. I have provided code below. I don't understand why my code is not working, any help would be greatly appreciated.

document.getElementById('input').addEventListener("input",
function(){
  var userInput = document.getElementById('input').value;
  if(!isNaN(userInput)){
    alert("Is a number");
  }
  else{
    alert("Is not a number");
  }

},true);
User Input : <input id="input">


Solution

  • you can use typeof

    var userInput = document.getElementById('input').value;
    if(typeof userInput == 'number')){
      console.log("Is a number");
    }else{
      console.log("Is not a number");
    }