将输入框限制为仅数字0-9 [英] Restricting an input box to only numbers 0-9

查看:637
本文介绍了将输入框限制为仅数字0-9的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

因此,如果用户要输入az中的任何内容,则无法在输入框中使用。

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.

请不要jQuery。

no jQuery please.

<!DOCTYPE html>

<html>

<head>

</head>

<body>

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

</body>

</html>


推荐答案

您可以使用HTML5 <$ c的输入$ c>数字类型

You could use an input with the HTML5 number type

<input type="number" />

或javascript,输入数字类型不会真正限制仅输入数字:

or javascript, as an input with a number type doesn't really limit input to numbers only :

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

这篇关于将输入框限制为仅数字0-9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆