Java Script: Get Key Codes

 Java Script     sbo     Updated on Feb 23, 2014     VIKRAM     517   

Introduction:

In this article i will explain how to get key codes in Java Script.

Description:

In previous articles i explained How to replace string in SQL ServerHow to replace string in C#How to replace string in Java Script, and How many ways we can replace the string in Java Script. Now i will explain how to get key codes in Java Script.

Example:

To get key code write the following code and press any key, then it will display Key and Key Code.

Source:

    <div>
        <span id="Key"></span>&nbsp;&nbsp;&nbsp;<span id="KeyCode"></span>
    </div>

Java Script:

    <script type="text/javascript">
        document.onkeypress = function (evt) {
            evt = evt || window.event;
            var charCode = evt.keyCode || evt.which;
            $("#KeyCode").html('Key Code: ' + charCode);
            var charStr = String.fromCharCode(charCode);
            $("#Key").html('Key : ' + charStr);
        };
    </script>

Full Source Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="KeyRestriction.aspx.cs" Inherits="KeyRestriction" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Key Codes - Java Script</title>
    <script src="Scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        document.onkeypress = function (evt) {
            evt = evt || window.event;
            var charCode = evt.keyCode || evt.which;
            $("#KeyCode").html('Key Code: ' + charCode);
            var charStr = String.fromCharCode(charCode);
            $("#Key").html('Key : ' + charStr);
        };
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <span id="Key"></span>&nbsp;&nbsp;&nbsp;<span id="KeyCode"></span>
    </div>
    </form>
</body>
</html>

Note: To check the output click in result window and then press any key.

Demo:

  Related Articles
Check/Uncheck checkboxes when parent checkbox is checked/unchecked and vice-versa in Java Script
Java Script: Number Validation
Java Script: Create/Insert rows dynamically to HTML Table and Remove/Delete rows from HTML Table
Java Script: Create HTML Table dynamically
Java Script: TextBox
  Recent Articles
Check/Uncheck checkboxes when parent checkbox is checked/unchecked and vice-versa in Java Script
Java Script: Number Validation
Java Script: Create/Insert rows dynamically to HTML Table and Remove/Delete rows from HTML Table
Java Script: Create HTML Table dynamically
Java Script: TextBox