Skip to content Skip to sidebar Skip to footer

String.fromcharcode Not Working On Keydown Event

I am tyring to read the input characters on keydown event and try to process them. When I am triing to convert them into character using 'String.fromCharCode(key);' Its always givi

Solution 1:

Guess you only need to change the EventListener to keypress

var inp = document.getElementById("ti");

inp.addEventListener("keypress", onKeyDown);

functiononKeyDown(e) {
    if (window.event) {
        var key = window.event.keyCode;
    } else {
        var key = e.keyCode;
    }
    document.getElementById("output").innerHTML += String.fromCharCode(key);
}

Fiddle: http://jsfiddle.net/zZtW9/4/

Take a look here,you can note learn the differences from here : http://www.w3resource.com/html/attributes/HTML-event-attributes-completed.php

EDIT: For your doubt,check this : keyup event always return uppercase letter

Solution 2:

Try keypress instead of keydown

 inp.addEventListener("keypress", onKeyDown);

In theory, the keydown and keyup events represent keys being pressed or released, while the keypress event represents a character being typed. The implementation of the theory is not same in all browsers.

DEMO

Solution 3:

I wrote a module called keysight that translates keypress, keydown, and keyup events into characters and keys respectively.

Example:

 inp.addEventListener("keydown", function(event) {
    var character = keysight(event).char
    document.getElementById("output").innerHTML +=  character
 })

Post a Comment for "String.fromcharcode Not Working On Keydown Event"