jQuery: Filter out non-printable keypress events

0 Comments

Its pretty handy to listen in for keydown, keyup and keypress events, but it also listens in for a bunch of stuff that, most of the time, we're really not interested in (such as ESC, Tab, F1-F12, backspace, CTRL+C, ALT+Tab, etc).

To filter out those extra triggers we don't need, add the following check at the start of your event handler:

1.// Filter out special keys
2.if (e.charCode && !e.originalEvent.altKey && !e.originalEvent.ctrlKey) {
3.  alert('OK');
4.}
5.else {
6.  alert('DUD');
7.}

"e.charCode" will excluse the majority of the non printable keypresses. If you want to keep a specific key (such as backspace, which is useful for searching), then use the following snippet to check for the corresponding key code you want.

1.var code = (e.keyCode || e.which);

This ensures its compatible with more browsers.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog