目录

onkeypress Event

Example

Call a function when the user presses a key:

<input type="text" onkeypress="myFunction()">
Try it Yourself »

More examples below.


Description

The onkeypress event occurs when the user presses a key on the keyboard.

Keyboard Events

Event Occurs When
onkeydown The user presses a key
onkeypress The user presses a key
onkeyup the user releases a key

See Also:

The Keyboard Event Object

Warning

The onkeypress event is deprecated.

It is not fired for all keys (like ALT, CTRL, SHIFT, ESC) in all browsers.

To detect if the user presses a key, always use the onkeydown event. It works for all keys.



Syntax

In HTML:

< element onkeypress=" myScript">
Try it Yourself »

In JavaScript:

object.onkeypress = function(){ myScript};
Try it Yourself »

In JavaScript, using the addEventListener() method:

object.addEventListener("keypress", myScript);
Try it Yourself »

Technical Details

Bubbles: Yes
Cancelable: Yes
Event type: KeyboardEvent
HTML tags: All HTML elements, EXCEPT: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>
DOM Version: Level 2 Events

Browser Support

onkeypress is a DOM Level 2 (2001) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11