问题:
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
>