In this article I will explain how to solve the issue JavaScript window.event.keyCode not working in Internet Explorer (IE), Mozilla FireFox, Chrome, Safari and Opera browsers.
I will show how to get the ASCII keyCode on JavaScript KeyPress, KeyUp and KeyDown events.
This is a common issue faced by many when they use event.keyCode to get the key ASCII value in browsers other than Internet Explorer. So what to do?
But the fact is Mozilla Firefox has event.keyCode event only difference is the place where you use it
https://developer.mozilla.org/En/DOM/Event.keyCode
ASCII Code on keypress event
Mozilla Firefox
Mozilla Firefox has the ASCII code of all keys in the event.keyCode whenever it is called on keyup and keydown events. But when you call it on keypress event it stores the ASCII codes of all keys that produce a character that is visible 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.
Internet Explorer, Chrome, Safari
IE, Chrome and Safari has ASCII code of only character keys when called on keypress event.
Opera
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.
<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>
<asp:TextBox ID="TextBox1" runat="server" onkeypress = "GetKeyCode(event)" />
<input id="Text1" type="text" onkeypress = "GetKeyCode(event)"/>
ASCII Code on keyup and keydown events
In keyup and keydown events you can get ASCII codes of all the keys in
Internet Explorer, Mozilla Firefox, Google Chrome, Opera and Apple Safari using the following JavaScript function
<script type = "text/javascript">
function GetKeyCode(evt)
{
alert("You pressed : " + evt.keyCode);
}
</script>
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)"/>
Hope you liked it.