如何防止keydown上的数字输入? [英] How to prevent number input on keydown?
问题描述
我要防止在textfield上的 keydown事件上输入数字,并运行自定义处理函数。这是问题
-
e.target.value
尚未投影到目标值 -
e.keyCode
取决于键盘类型,语言布局,Fn或Shift键 -
String.fromCharCode(e.keyCode)
不可靠,至少在我的键盘(捷克qwerty) - w3规范表示
e.keyCode
是一个旧属性,建议e.char
那么如何在文本字段中显示之前捕获数字输入?
使用 keypress
事件。它是唯一的关键事件,它将通过大多数浏览器中的
属性和(混淆地) keyCode / code>属性。使用它,您可以有条件地抑制基于键入的字符的
keypress
事件。但是,这不会帮助您阻止用户在包含数字字符的文本中粘贴或拖动,因此您仍需要某种额外的验证。
我最喜欢的引用JavaScript关键事件: http://unixpapa.com/js/key.html
textBox.onkeypress = function(e){
e = e || window.event;
var charCode =(typeof e.which ==undefined)? e.keyCode:e.which;
var charStr = String.fromCharCode(charCode);
if(/\d/.test(charStr)){
return false;
}
};
I want to prevent number input on keydown event on textfield and run custom handler function. Here are the issues
e.target.value
is useless since the key value is not projected into the target value yete.keyCode
for number depends on keyboard type, language layout, Fn or Shift keyString.fromCharCode(e.keyCode)
is not reliable, at least on my keyboard (Czech qwerty)- w3 specification says
e.keyCode
is a legacy attribute and suggestse.char
instead, but it is not implemented in browsers yet
So how to catch the number input before it appears in the textfield?
Use the keypress
event instead. It's the only key event which will give you information about the character that was typed, via the which
property in most browsers and (confusingly) the keyCode
property in IE. Using that, you can conditionally suppress the keypress
event based on the character typed. However, this will not help you prevent the user from pasting or dragging in text containing numeric characters, so you will still need some kind of extra validation.
My favourite reference for JavaScript key events: http://unixpapa.com/js/key.html
textBox.onkeypress = function(e) {
e = e || window.event;
var charCode = (typeof e.which == "undefined") ? e.keyCode : e.which;
var charStr = String.fromCharCode(charCode);
if (/\d/.test(charStr)) {
return false;
}
};
这篇关于如何防止keydown上的数字输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!