Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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">
like image 754
Ayma Avatar asked Jan 02 '23 11:01

Ayma


1 Answers

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");
}
like image 179
mstfyldz Avatar answered Jan 04 '23 05:01

mstfyldz