views:

1993

answers:

4

how can i convert a char to its respective keycode.

+5  A: 

You can use the

charCodeAt

function to achieve this.

Working demo

Eg:

<SCRIPT>

function showKeyCode()
{
    var character = document.getElementById ( "character" ).value.substring(0,1);
    var code = document.getElementById ( "character" ).value.charCodeAt(0);
    var msg = "The Key Code for the \""+character+"\" character is "+code+".";
    alert(msg);
}
</script>


<input type="text" id="character" size="15">
<input type="button" value="Show Key Code" onclick="showKeyCode();">
rahul
i'm having a char let say 'a' and i need to find the respective keycode of 'a'.
santose
I'm not sure whether this really answers the question - it depends what you mean by "keycode". This function gives you the character code, not the key code, which may not be the same thing.
Tim Down
+1  A: 

Find a keycode/ascii chart like this one and put it into an array such that array['char'] = keycode. This is tedious, but the code will execute pretty fast.

Jacob
A: 

What do you mean by "keyCode"? Different browsers have different keyCode values in keyup and keydown events which will not necessarily correspond to the ASCII code for the corresponding character. For alphanumeric keys, the keypress event will give you the ASCII code in most browsers via the charCode or which properties. This page is useful.

Tim Down