views:

141

answers:

3

I have made following code, but whatever I type it will always print some odd char.

$(document).keypress(function(event) {
        var character = String.fromCharCode(event.keyCode);
        $("body").append(character);
        event.preventDefault(); 
        return false;
    });
A: 

You can't use String.fromCharCode() for this purpose. You can write your own function that could recognize the characters.

pako
A: 

keyCode is not the same as a charCode, they are different maps (And differ somewhat between browsers with arrow keys and such).

Think about it this way, what letter is Escape, or Delete?

Nick Craver
that is right. For instance, keyCode 13 means the enter key, if my memory is still working... So you must figure out the mapping between English letters to their corresponding keycode so to finish the code.
Michael Mao
A: 

change keyCode to charCode and Your code works. But this might not be a good idea - it's not cross browser I think. And it returns non-ascii chars as well (when you click tab key etc.) so you'd have to filter them out.

If You wanted a practical application try using an input field and get its text on keypress or something like that

naugtur