仅允许在输入文本上使用数字,退格键和删除键 [英] Only allow numbers, backspace and delete keys on input text

查看:259
本文介绍了仅允许在输入文本上使用数字,退格键和删除键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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 )

查看小提琴 查看全文

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