9

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.

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

no jQuery please.

<!DOCTYPE html>

<html>

<head>

</head>

<body>

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

</body>

</html>
4

2 回答 2

30

您可以使用 HTML5number类型的输入

<input type="number" />

或 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();
});

小提琴

于 2013-08-09T22:54:56.823 回答
6

使用 HTML5

<input type="number">

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

于 2013-08-09T22:54:04.303 回答