English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

HTML Reference Manual

Complete list of HTML tags

HTML onkeypress event attribute

The onkeypress attribute is used to get or set the event handler function for the keypress event of the current element.

HTML Event Attributes

Online Example

Run the script when a key is pressed:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>Basic Tutorial(oldtoolbag.com)</title> 
<script>
function displayResult()
{
    var x;
    if(window.event) // IE8 and earlier IE versions
    {
        x=event.keyCode;
    }
    else if(event.which) // IE9/Firefox/Chrome/Opera/Safari
    {
        x=event.which;
    }
    keychar=String.fromCharCode(x);
    alert("Key pressed " + keychar + "Key pressed");
}
</script>
</head>
<body>
<p>The function is triggered when the user presses a key in the input field. It reminds the pressed key.</p>
<input type="text" onkeypress="displayResult()">
</body>
</html>
Test and see ‹/›

Browser compatibility

IEFirefoxOperaChromeSafari

All mainstream browsers support the onkeypress event attribute

Definition and Usage

The onkeypress attribute is triggered when the user presses a key (on the keyboard).

Tip: Event trigger sequence related to onkeypress event:

  • onkeydown

  • onkeypress

  • onkeyup

  • Note: onkeypress event cannot trigger all keys in all browsers (e.g., ALT, CTRL, SHIFT, ESC) . If you only want to detect whether a key has been pressed by the user, Can be used onkeydown Replaced, onkeydown is triggered by all keys.

    Note: The onkeypress attribute cannot be used with the following elements: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, or <title>.

    HTML 4.01 With HTML5Differences

    None.

    Syntax

    <element onkeypress="script">

    Attribute Value

    ValueDescription
    scriptSpecifies the script to be executed when the onkeypress event is triggered.
    HTML Event Attributes