Saturday, March 19, 2011

javascript detect and capture keyboard keycode

These is how to capture what user have type in their keyboard
The captured data is the "keycode" which is an integer

Like 'enter' key, the code is 13

Some data that I have discover and might be usefull to others and myself
These was tested and the same for IE, Firefox, Google Chrome and Safari
a until z keycode 97 until 122
A until Z keycode 65 until 90
0 until 9 keycode 48 until 57


Lets get to the code

function whatKeyCodeHaveIType( theEvent)
{
    charCode = (theEvent.which) ? theEvent.which : theEvent.keyCode

    theTempoElement = document.getElementById('thisiswhatyouhavetpye');
    theTempoElement.innerHTML = theTempoElement.innerHTML + ', ' + charCode;

    //This is to ignore "ENTER" key. Its usefull to prevent a form from autosubmit if you press enter
    return (charCode != 13);
}

//Later in HTML, use these
<input id="whatyouhavetype" style="width: 500px;" onkeypress="return whatKeyCodeHaveIType(event);"/>
<textarea id="thisiswhatyouhavetpye" cols="70" rows="5"></textarea>

Type something here :


No comments: