Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reject "control" keys on keyDown event

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

like image 332
contactmatt Avatar asked Oct 14 '11 16:10

contactmatt


4 Answers

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);
    }
}
like image 134
contactmatt Avatar answered Oct 02 '22 07:10

contactmatt


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.

like image 33
Blazemonger Avatar answered Oct 02 '22 07:10

Blazemonger


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
}
like image 44
Tomáš Vavřinka Avatar answered Oct 02 '22 09:10

Tomáš Vavřinka


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
    }
})
like image 44
Rob W Avatar answered Oct 02 '22 08:10

Rob W