Javascript 仅当键是字母或数字时才对 keyup 发出警报
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5271129/
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
do an alert on keyup only if the key is a letter or number
提问by Omu
I would like to show an alert on keyup event but only if the key was a letter or a number, not for shift,tab etc.
我想在 keyup 事件上显示警报,但前提是键是字母或数字,而不是 shift、tab 等。
<input type='text' id='hi />
or for any key except for tab, shift, ctrl, enter
或者对于除 tab、shift、ctrl、enter 之外的任何键
anybody knows how ?
有人知道怎么做吗?
回答by The_Butcher
回答by Tim Down
If you want to check which character was typed, keyup
is the wrong event. Only the keypress
event can reliably tell you anything about the character typed. You can do it as follows:
如果你想检查输入的keyup
是哪个字符,是错误的事件。只有keypress
事件可以可靠地告诉您有关键入的字符的任何信息。你可以这样做:
$("#hi").keypress(function(e) {
var charTyped = String.fromCharCode(e.which);
if (/[a-z\d]/i.test(charTyped)) {
alert("Letter or number typed: " + charTyped);
}
});
回答by zfrisch
This appended code accounts for numbers, characters, and digits from the numpad:
此附加代码说明了数字键盘中的数字、字符和数字:
document.querySelector(selector).addEventListener('keypress', function() {
if (e.which <= 90 && e.which >= 48 || e.which >= 96 && e.which <= 105) {
alert('keycode ' + e.which + ' triggered this event');
//do whatever
}
});
回答by Mendy
回答by lordlouis
I never liked the key code validation. My approach was to see if the input have text (any character), confirming that the user is entering text and no other characters.
我从不喜欢关键代码验证。我的方法是查看输入是否有文本(任何字符),确认用户正在输入文本而不是其他字符。
$('#input').on('keyup', function() {
var words = $(this).val();
// if input is empty, remove the word count data and return
if(!words.length) {
$(this).removeData('wcount');
return true;
}
// if word count data equals the count of the input, return
if(typeof $(this).data('wcount') !== "undefined" && ($(this).data('wcount') == words.length)){
return true;
}
// update or initialize the word count data
$(this).data('wcount', words.length);
console.log('user tiped ' + words);
// do you stuff...
});
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input type="text" name="input" id="input">
</body>
</html>
回答by Kimtho6
<input id="textbox" type='text' id='hi />
$("#textbox").keypress(function (e){
if (e.which <= 90 && e.which >= 48)
{
alert('Letter or number click');
}
});
回答by david
<input type="text" id="hi" onkeypress="keyPress()" />
function keyPress(e){
var key, x = e || window.event; key = (x.keyCode || x.which);
if(key <= 90 && key >= 48){
alert("Key pressed");
}
}