javascript 只允许输入文本上的数字、退格和删除键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29748005/
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-28 11:00:11  来源:igfitidea点击:

Only allow numbers, backspace and delete keys on input text

javascriptjqueryhtml

提问by VansFannel

I have this input text in a HTML5 page:

我在 HTML5 页面中有这个输入文本:

<input type="text" class="quantity" 
onkeypress='return (event.charCode >= 48 && event.charCode <= 57) || event.charCode == 8 || event.charCode == 46' required />

Because I need an input text that does allow only numbers, but I could need also delete a number. When I press backspace or delete nothing happens.

因为我需要一个只允许数字的输入文本,但我可能还需要删除一个数字。当我按退格键或删除时,什么也没有发生。

The code above only allows numbers. How can I allow also backspace and delete?

上面的代码只允许数字。我怎样才能允许退格和删除?

回答by steo

keypresseventgives only output of letters code. Use keydowninstead.

keypressevent只给出字母代码的输出。使用keydown来代替。

The keypress event is fired when a key is pressed down and that key normally produces a character value (use input instead).

当一个键被按下并且该键通常会产生一个字符值时会触发 keypress 事件(使用 input 代替)。

<input type="text" class="quantity" 
onkeydown='return (event.which >= 48 && event.which <= 57) 
   || event.which == 8 || event.which == 46' required />

I'm using e.whichbecause keydownproduce it but, as the doc says, whichis deprecated and keyshould be used instead ( even if not fully implemented )

我正在使用e.which因为keydown生产它,但正如文档所说,which已被弃用,key应改为使用(即使没有完全实现)

Check out the Fiddleand keypress docs

查看Fiddlekeypress 文档

回答by Johnny Blaze

this jquery function does it

这个 jquery 函数做到了

$('#id').keypress(function(e) {
            var a = [46];
            var k = e.which;
            console.log( k );
                a.push(8);
                a.push(0);

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

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

回答by R4nc1d

You shouldn't use the keypress event, but the keyup or keydown event because the keypress event is intented for real (printable) characters. "keydown" is handled at a lower level so it will capture all non-printing keys like DEL and ENTER

您不应使用 keypress 事件,而应使用 keyup 或 keydown 事件,因为 keypress 事件旨在用于真实(可打印)字符。“keydown”在较低级别处理,因此它将捕获所有非打印键,如 DEL 和 ENTER