onkeypress event | keypress event
Occurs on an element that has the focus when a key is pressed down and occurs periodically until the key is released.
The onkeypress event is not fired for all key types in all browsers. For details, please see the table below. onkeydown and onkeypress events, because sometimes the onkeydown event, sometimes the onkeypress event needs to be canceled depending on the browser and the type of the pressed key. For example, if you want to cancel the cursor left, up, right and down keys, the onkeydown event needs to canceled in Internet Explorer, Firefox, Google Chrome and Safari and the onkeypress event needs to be canceled in Opera. For alphanumeric characters, canceling one of the onkeydown and onkeypress events is sufficient.
The following table describes what keys fire the onkeypress event in different browsers:
|Google Chrome and Safari
|Alphanumeric, +, -, *, /, ENTER, SPACE
|ALT, CTRL, META, SHIFT
|Fn, cursor left, up, right and down keys, Insert, Delete, Home, End, Page Up, Page Down, Backspace
How to register:
|object.onkeypress = handler;
|object.addEventListener ("keypress", handler, useCapture);
|object.attachEvent ("onkeypress", handler);
You can find the related objects in the Supported by objects section below.
The event object is accessible to all event handlers in all browsers. The properties of the event object contain additional information about the current event. To get further details about these properties and the possible event handler registration methods, please see the page for the event object.
Actions that invoke the onkeypress event:
- Pressing a key.
- Holding down a key.
The order of events related to the onkeypress event:
Example HTML code 1:
This example illustrates the use of the onkeypress event:
Example HTML code 2:
This is another example for the onkeypress event:
Example HTML code 3:
This example shows how to create a text field that does not accept numeric input:
User Contributed Comments