javascript 限制输入框只能输入数字 0-9

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18156824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:54:46  来源:igfitidea点击:

Restricting an input box to only numbers 0-9

javascript

提问by John Smith

How can one restrict an inputbox to just use numbers only.

如何限制输入框只使用数字。

So if a user were to type in anything from a-z, it will not work in the inputbox.

因此,如果用户要从 az 输入任何内容,它将无法在输入框中工作。

To some this may seem easy but to me, it sounds like rocket science.

对某些人来说,这似乎很容易,但对我来说,这听起来像是火箭科学。

no jQuery please.

请不要使用jQuery。

<!DOCTYPE html>

<html>

<head>

</head>

<body>

<input type="text" id="numbersonly" />

</body>

</html>

回答by adeneo

You could use an input with the HTML5 numbertype

您可以使用 HTML5number类型的输入

<input type="number" />

or javascript, as an input with a numbertype doesn't really limitinput to numbers only :

或 javascript,作为具有number类型的输入并没有真正将输入限制为数字:

document.getElementById('numbersonly').addEventListener('keydown', function(e) {
    var key   = e.keyCode ? e.keyCode : e.which;

    if (!( [8, 9, 13, 27, 46, 110, 190].indexOf(key) !== -1 ||
         (key == 65 && ( e.ctrlKey || e.metaKey  ) ) || 
         (key >= 35 && key <= 40) ||
         (key >= 48 && key <= 57 && !(e.shiftKey || e.altKey)) ||
         (key >= 96 && key <= 105)
       )) e.preventDefault();
});

FIDDLE

小提琴

回答by doitlikejustin

Using HTML5

使用 HTML5

<input type="number">

You can also use Modernizrfor backwards compatibility

您还可以使用Modernizr来实现向后兼容性