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
Only allow numbers, backspace and delete keys on input text
提问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
keypress
event
gives only output of letters code. Use keydown
instead.
keypress
event
只给出字母代码的输出。使用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.which
because keydown
produce it but, as the doc says, which
is deprecated and key
should be used instead ( even if not fully implemented )
我正在使用e.which
因为keydown
生产它,但正如文档所说,which
已被弃用,key
应改为使用(即使没有完全实现)
Check out the Fiddleand keypress docs
回答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