且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将文本字段限制为仅数字的***方法?

更新时间:2023-02-24 19:50:36

这是我另一次为数字制作的东西,它也将允许所有格式化程序.

This is something I made another time for just numbers, it will allow all the formatters as well.

$('input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!(a.indexOf(k)>=0))
        e.preventDefault();
});​

试试看

http://jsfiddle.net/zpg8k/

请注意,为了粘贴/上下文菜单和不支持粘贴事件的浏览器,您还需要在提交/服务器端进行过滤.

As a note, you'll want to filter on submit/server side as well, for sake of pasting/context menu and browsers that don't support the paste event.

我看到您在已接受"的答案周围蹦蹦跳跳,所以我会澄清一些事情.您可以真正使用此处列出的任何方法,它们都有效.我个人会使用我的实时客户端过滤,然后在提交和服务器端使用其他人建议的 RegEx.但是,没有任何客户端本身是 100% 有效的,因为没有什么能阻止我输入 document.getElementById('theInput').value = 'Hey, letters.';代码>在控制台中并绕过任何客户端验证(轮询除外,但我也可以从控制台取消 setInterval ).使用您喜欢的任何客户端解决方案,但请确保您在提交和服务器端也实现了一些东西.

I see you're bouncing around the 'accepted' answer, so I'll clear something up. You can really use any of the methods listed here, they all work. What I'd personally do is use mine for live client side filtering, and then on submit and server side use RegEx as suggested by others. However, no client side by itself will be 100% effective as there is nothing stopping me from putting document.getElementById('theInput').value = 'Hey, letters.'; in the console and bypassing any clientside verification (except for polling, but I could just cancel the setInterval from the console as well). Use whichever client side solution you like, but be sure you implement something on submit and server side as well.

好的,根据评论,我不得不调整两件我没有想到的事情.首先,keypress 而不是 keydown,它已经更新,但是 IE 中缺少 indexOf(严重的是 Microsoft!?)也破坏了上面的示例.这是另一种选择

Alright, per the comments I had to adjust two things I didn't think of. First, keypress instead of keydown, which has been updated, but the lack of indexOf in IE (seriously Microsoft!?) breaks the example above as well. Here's an alternative

$('input').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!($.inArray(k,a)>=0))
        e.preventDefault();
});​

新的 jsfiddle:http://jsfiddle.net/umNuB/

New jsfiddle: http://jsfiddle.net/umNuB/