charCodeEvent Property

事件对象参考手册Event Object

Example

Get the Unicode value of the pressed keyboard key:

var x = event.charCode;

xThe output result is:

119 // 119 is the letter "w"

Try it Yourself »

More examples are included at the bottom of this article.


Definition and Usage

The charCode property returnsonkeypressthe character code of the key value that triggered the event.

A Unicode character code is a number for a letter (for example, the number "97" represents the letter "a").

Tip:A list of all Unicode characters can be found in ourComplete Unicode Reference Manual。

Tip:If you need to convert a Unicode value to a character, you can use thefromCharCode()method.

Note:If this property is used for theonkeydownoronkeyupevent, the return value is always "0".

Note:This property is read-only.

Note:The which and keyCode properties provide a way to solve browser compatibility. The latest version of DOM events recommends using thekeyproperty to replace this method.

Note:IE8 and earlier versions do not support the which property. Unsupported browsers can use thekeyCodeproperty. However, the keyCode property is invalid in the onkeypress event in Firefox. To be compatible with these browsers, you can use the following code:

var x = event.charCode || event.keyCode; // UsecharCodeorkeyCode, this supports different browsers.

Tip:You can also use the keyCode property to detect special keys (such as "caps lock" or arrow keys). The keyCode and charCode properties provide a way to solve browser compatibility. The latest version of DOM events recommends using thekeyproperty to replace this method.

Tip:If you want to check whether the "ALT", "CTRL", "META", or "SHIFT" key is pressed, you can use thealtKey, ctrlKey, metaKeyorshiftKeyproperty.


Browser Support

The numbers in the table indicate the first browser version that supports the property.

Property
charCode Yes 9.0 Yes Yes Yes


Syntax

event.charCode

Technical Details

Return Value: A number representing the Unicode character code
DOM Version: DOM Level 2 Events


Examples

More Examples

Example

Browser-compatible solution for getting the Unicode value of a key:

// If the browser does not support charCode, use keyCode (IE8 and earlier versions)
var x = event.charCode || event.keyCode;

Try it Yourself »

Example

When the user presses the "O" key, a prompt message is displayed:

function myFunction(event) {
    var x = event.charCode || event.keyCode;
    if (x == 111 || x == 79) { // o is 111, O is 79
        alert("You pressed the 'O' key!");
    }
}

Try it Yourself »

Example

Convert Unicode value to character:

var x = event.charCode || evt.keyCode;   // Get the Unicode value
var y = String.fromCharCode(x);          // Convert the value to a character

Try it Yourself »


Related Pages

HTML DOM Reference:key Event Property

HTML DOM Reference:keyCode Event Property

HTML DOM Reference:which Event Property


事件对象参考手册Event Object

Other Extensions