In this article I will explain with an example, how to get the keyCode of pressed key on Keyboard using JavaScript in ASP.Net.
 
 

Explanation

ASCII Code on keyup and keydown events

1. Mozilla Firefox has the ASCII code of all keys in the event.keyCode, which means whenever it is used on keyup and keydown event handler, you will get the keyCode of the pressed or released key.
But when you call it on keypress event it stores the ASCII codes of all keys that produce a character that is visibile like A - Z, 0 - 9, and other character keys in charCode while keyCode has ASCII codes of all non-character keys like BACKSPACE, SHIFT, CTRL, etc.
2. Internet Explorer (IE), Edge, Chrome and Safari has ASCII code of only character keys when called on keypress event.
3. In Opera you will get ASCII code of the all the keys in the event.keyCode event.
So in case when you want to get ASCII codes on keypress event you will need to use the following function.

JavaScript

<script type = "text/javascript">
    function GetKeyCode(evt)
    {
        var keyCode;
        if(evt.keyCode > 0)
        {
            keyCode = evt.keyCode;
        }
        else if(typeof(evt.charCode) != "undefined")
        {
            keyCode = evt.charCode;
        }
        alert("You pressed : " + keyCode);
    }
</script>
 
 

HTML Markup

keyup

<asp:TextBox ID="TextBox1" runat="server" onkeyup="GetKeyCode(event)" />
<input id="Text1" type="text" onkeyup="GetKeyCode(event)"/>
 

keydown

<asp:TextBox ID="TextBox1" runat="server" onkeydown="GetKeyCode(event)" />
<input id="Text1" type="text" onkeydown="GetKeyCode(event)"/>
 
 

Screenshot

Find Keyboard keyCode using JavaScript
 
 

Browser Compatibility

The above code has been tested in the following browsers.
Microsoft Edge  FireFox  Chrome  Safari  Opera
* All browser logos displayed above are property of their respective owners.
 
 

Demo

 
 

Downloads