-1

I need to catch some characters from keyboard and I have to use jquery keydown(not keypress).

I know some of you will recommend to use keypress but I have to use keydown and I only need 3 characters to catch with keydown function.(chars: A,F,X)

Here is my code.

$("#keypage").keydown(function(e){
  var keycode = e.keyCode;
  if( keycode === 65 || keycode === 70 || keycode === 88) {
    var char = String.fromCharCode(keycode);
  }

  // do something with char
});

Is there a problem with that approach?

EDIT: I asked this question because I want to know that if keydown has a problem for chars with this approach.

javauser35
  • 1,177
  • 2
  • 14
  • 34

1 Answers1

0

If you just wanted to check only the mentioned Characters then it is fine to use keydown

The keypress events are generally the easiest to work with. They are likely to cause substantially fewer problems with non-US keyboard layouts and it's not too hard to identify which key was pressed. You can get the character typed by doing:

if (event.which == null)
  char= String.fromCharCode(event.keyCode);    // old IE   
else if (event.which != 0 && event.charCode != 0)
  char= String.fromCharCode(event.which);     // All others   
else
  // special key 

What to do with keypress events on special keys is a problem. I recommend pretending they never happened. If you really want to process special key events, you should probably be working with keydown and keyup instead. For keydown and keyup events, you can identify most common keys (letters, numbers, and a few others) by just looking at the event.keyCode and more or less pretending that it is an ASCII code. However, it isn't really, and the many Javascript manuals that say it can be converted to a character by doing String.fromCharCode(event.keyCode) are wrong. On keydown and keyup events, the keycodes are not character codes, and this conversion will give wild results for many keys. There is no general portable way to convert keycodes to characters.

Because of bugs, many keys cannot be distinguished on keydown and keyup in Macintosh Gecko.

Now if you need to check complex key codes and their hashes then keypress is the best option. for more details you can read keydown, keypress and keyup events detail on this link

Ghulam Mohayudin
  • 1,093
  • 10
  • 18