keyCode property (event)
Sets or retrieves the Unicode character code of the key that generated the onkeypress event and the Unicode key code of the key that generated the onkeydown and onkeyup events.
- In Google Chrome, Safari and Internet Explorer from version 9, the keyCode and charCode properties are identical for the onkeypress events.
- In Firefox, if the pressed key generates a character, the charCode property contains the character code, else the keyCode property.
- In Firefox, Opera, Google Chrome, Safari and Internet Explorer from version 9, the which property can also be used, it always returns the Unicode character code of the key that was pressed for onkeypress events.
You can find the related objects in the Supported by objects section below.
The keyCode property is read-only in Firefox, Opera, Google Chrome and Safari, and it is read/write in Internet Explorer.
Integer that specifies or retrieves the Unicode character or key code.
Predefined constants are available for the possible Unicode key codes, in the scope of the KeyboardEvent interface. You can use them directly through the KeyboardEvent interface (KeyboardEvent.DOM_VK_A) or through an instance of the event object. For further details, please see the page for the KeyboardEvent interface. Unfortunately, these constants are only supported by Firefox, so use the numeric values instead of the predefined constants for a cross-browser solution.
Default: this property has no default value.
Example HTML code 1:
This example illustrates the use of the keyCode property:
Example HTML code 2:
This example shows how to create a text field that does not accept numeric input:
Example HTML code 3:
This example is same as the previous one, but it uses the onkeypress event instead of the onkeydown event:
User Contributed Comments