如何检查用户输入是否为数字?

时间:2018-12-25 05:56:30

标签: javascript numbers

我想检查用户输入的数字是否; “输入”来自html输入标签。我在下面提供了代码。我不明白为什么我的代码无法正常工作,我们将不胜感激。

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

5 个答案:

答案 0 :(得分:3)

您可以使用typeof

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

答案 1 :(得分:2)

这里已经有很多好的答案,但是我可以想到的另一种方法是像下面这样将字符串与0进行比较

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

仅当其为数字时才返回true。但是要注意的是,如果它是一个空字符串,它也将返回true。因此,如果您确定用户输入了至少一个字符/数字,或者您已经在处理空的输入大小写,则可以使用。

答案 2 :(得分:1)

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

仅接受数字。

答案 3 :(得分:1)

尝试一下。

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>

答案 4 :(得分:1)

您可以使用typeof进行验证。

> a = 10
10
> typeof a
'number'

> if(typeof a === 'number') { console.log("Number") } else { console.log("Not a Number") }
Number
undefined
>