What is the cleanest way in开发者_开发问答 JavaScript or jQuery to filter out control keys. By control keys, I mean any key that IS NOT A-Z, 0-9, or special characters (i.e. !, @, #, etc.). I simply want to filter out keys such as 'Shift', 'Alt', F1- F9, Caps Lock, etc.
I'm sure I could check each individual ASCII code from the event argument...but I'm wondering if there is a "cleaner" solution.
Note: I'm developing an application specifically for IE 8
I went with something like this:
function (e, inputElement) {
// If the user gives the textbox any keyboard input, mark the input box as "dirty"
var scope = this;
var k = e.which;
// Verify that the key entered is not a special key
if (k == 20 /* Caps lock */
|| k == 16 /* Shift */
|| k == 9 /* Tab */
|| k == 27 /* Escape Key */
|| k == 17 /* Control Key */
|| k == 91 /* Windows Command Key */
|| k == 19 /* Pause Break */
|| k == 18 /* Alt Key */
|| k == 93 /* Right Click Point Key */
|| ( k >= 35 && k <= 40 ) /* Home, End, Arrow Keys */
|| k == 45 /* Insert Key */
|| ( k >= 33 && k <= 34 ) /*Page Down, Page Up */
|| (k >= 112 && k <= 123) /* F1 - F12 */
|| (k >= 144 && k <= 145 )) { /* Num Lock, Scroll Lock */
return false;
}
else {
scope.setPointValueDirtyStatus(inputElement, true);
}
}
Use event.which -- Each key has its own code. Control key is 17, shift key is 16, and @ is two different keys, 16 followed by 50. Use the demo on that page to find out what values are returned for each key you want to accept or ignore.
Kinda old topic but in 2021 event.which
is deprecated and event.keyCode
as well. However to get valid keys for user input you can go with just one simple condition.
if (event.key.length === 1) {
// do stuff
}
This will only allow a-z (codes 65 - 90), 0-9 (48 - 57). Note that shift
should be allowed, because it's necessary for transforming a text to an upper case.
$("...").keydown(function(ev){
var k = ev.which;
if(!(k >= 65 && k <= 90) /* a-z */
|| !(k >= 48 && k <= 57) /* numbers */
|| !(k >= 96 && k <= 111) /* numeric keyboard*/
|| k != 59 || k != 61 || k != 188 || k != 190 || k != 191 || k != 191
|| k != 192 || !(k >= 219 && k <= 222) || k != 32 /* Comma's, etc. */
|| ev.ctrlKey || ev.altKey/* || ev.shiftKey*/){
//Filter
}
})
精彩评论