仅允许在输入文本上使用数字,退格键和删除键 [英] Only allow numbers, backspace and delete keys on input text
问题描述
我在HTML5页面中有以下输入文本:
I have this input text in a HTML5 page:
<input type="text" class="quantity"
onkeypress='return (event.charCode >= 48 && event.charCode <= 57) || event.charCode == 8 || event.charCode == 46' required />
因为我需要一个只允许数字输入的文本,但是我可能还需要删除一个数字.当我按Backspace键或删除时,什么也没发生.
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?
推荐答案
keypress
event
仅给出字母代码的输出.使用keydown
代替.
keypress
event
gives only output of letters code. Use keydown
instead.
按下某个键时会触发keypress事件,并且该键通常会产生一个字符值(请改用input).
The keypress event is fired when a key is pressed down and that key normally produces a character value (use input instead).
<input type="text" class="quantity"
onkeydown='return (event.which >= 48 && event.which <= 57)
|| event.which == 8 || event.which == 46' required />
我之所以使用e.which
是因为keydown
会生成它,但正如文档所说,which
已过时,应改为使用key
(即使未完全实现)
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 )