1

How do I restrict a keydown event to only take effect when a character is pressed? I'd like to skip the code when a non-character is pressed on the keyboard, e.g. home button, end button.

I know I could target those buttons with e.which == someNumber but is there a better way to do it? Writing a condition for each non-character button doesn't seem like a good idea.

Thank you!

dork
  • 4,396
  • 2
  • 28
  • 56
  • 2
    To English characters only or any characters? Unicode support? Please elaborate. – VisioN Nov 14 '13 at 09:56
  • @VisioN any kind of character as long as it shows up on a textbox or something. – dork Nov 14 '13 at 09:58
  • I would put all the "authorized" key codes in a javascript array, then on key up test if e.which is in that array. To look into the array you can refer to [this post](http://stackoverflow.com/questions/143847/best-way-to-find-an-item-in-a-javascript-array) – Laurent S. Nov 14 '13 at 09:58
  • There's a length description here: http://unixpapa.com/js/key.html – Tobi Nov 14 '13 at 09:59
  • 1
    this may help you http://stackoverflow.com/questions/5534346/javascript-limit-text-input-characters – Prasanth K C Nov 14 '13 at 10:01

2 Answers2

1

try this

$(function () {
$(document).on('keydown', function (event) {
    if (event.keyCode == yourkeycode) {
        //stuff
    }
});
});
Linga
  • 10,379
  • 10
  • 52
  • 104
  • How is this solving his problem if he needs to still check for individual key codes? Does keydown in jquery not trigger non ascii characters? – Nick Nov 14 '13 at 18:39
0

You have to implement some form of range checking. Pick the range that takes the least amount of coding. What would you characterize as a character? Would it be everything between 32 and 125? Check out the range you're interested in on an ascii table.

Nick
  • 4,002
  • 4
  • 30
  • 41
  • I guess? So i could maybe just write e.which > 31 && e.which < 126? but those aren't the same, right? I mean e.which == 37 to 40 are arrow keys – dork Nov 14 '13 at 10:11
  • That range was just an example. Where do you see 37 to 40 being arrow keys? – Nick Nov 14 '13 at 10:18
  • I just did a console.log(e.which) and 37 to 40 are what comes out when arrows are pressed – dork Nov 15 '13 at 01:45
  • You are right. The AsciiTable is not used for the Keydown Event. I can't seem to find the doc for it, but try this site http://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes. The idea is to pretty much constrain your codes based off the chart. – Nick Nov 15 '13 at 02:06