Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - get character pressed - REGARDLESS of Keyboard

I am trying to retrieve the character inserted into a textfield/input with jQuery.

I use the usual:

var character = String.fromCharCode( e.keyCode || e.which );

method, but the only problem occurs when I use a different keyboard layout which I just noticed.

So for example, on a Standard US Keyboard it works perfectly. On a German Keyboard for instanece, if I have the language set to English - basically rendering it a standard US Keyboard, when I press the characters equivalent to :;'\,./[]=-, I get the German characters I actually see on my keyboard (although the English equivalent of then is added to the input).

Example: if I console.log( character ) for the folowing sentence I get:

  • In the input: []\';/.,
  • In the console: ÛݺÞܼ¾¿

My obvious question is, how can I make sure to get the true character inserter?

like image 505
Stefan Avatar asked Sep 25 '11 10:09

Stefan


2 Answers

The keypress event is different from the keyup and keydown events as it contains the key actually pressed. Try using that instead. Check it out with this snippet:

$('body').keypress(function(e){
  console.log('keypress', String.fromCharCode( e.which ));
});
$('body').keyup(function(e){
  console.log('keyup', String.fromCharCode( e.which ));
});
like image 143
Jørgen Avatar answered Oct 08 '22 09:10

Jørgen


What you can do is making the character appear in a hidden textbox and fetch the actual value. That way, you will get the character. You are currently passing the key code as if it is a character code. They are not the same.

http://jsfiddle.net/RQQpT/

(function() {
    var input = $("<input>").appendTo('body') // an hidden input element
                            .css({ position: "absolute",
                                   left:     -500,
                                   top:      -500       });

    $('body').bind({ keydown: function(e) {
                         input.focus(); // make characters appear in input element
                     },

                     keyup: function() {
                         var value = input.val(); // get value when key pressed

                         input.val(""); // reset value of input element

                         if(value) {
                             alert(value); // if there is a value, display it
                         }
                     }
                  });
})();
like image 32
pimvdb Avatar answered Oct 08 '22 09:10

pimvdb