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...

问题:

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">


回答1:

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");
}

回答2:

Many good answers already here, but another way I can think is to compare the string with 0 like following

"string" >= 0 || "string" <= 0

This return true only if its a number. But the catch is that it will also return true if its an empty string. So you can use if you know for sure that user enters at least one character/number or you are already handling the empty input case.


回答3:

<input type="text" onkeypress='return event.charCode >= 48 && event.charCode <= 57'>

accept only numbers.


回答4:

Try it like this.

function validate(){
  var userInput = document.getElementById('input').value;
  if(!isNaN(userInput)){
    console.log("Is a number");
  }else{
    console.log("Is not a number");
  }
}
<html>
<body>
<input type="text" id="input" onchange="validate()">
</body>
</html>


回答5:

You can use typeof to validate.

> a = 10
10
> typeof a
'number'

> if(typeof a === 'number') { console.log("Number") } else { console.log("Not a Number") }
Number
undefined
>
  • 发表于 2018-12-27 02:02
  • 阅读 ( 185 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除