W3cubDocs

/DOM

GlobalEventHandlers.onkeypress

The onkeypress property sets and returns the onKeyPress event handler code for the current element.

Syntax

element.onkeypress = event handling code

Notes

The keypress event should be raised when the user presses a key on the keyboard. However, not all browsers fire keypress events for certain keys.

Browser Incompatibilities

Webkit-based browsers (Google Chrome and Safari, for example) do not fire keypress events on the arrow keys

Firefox does not fire keypress events on modifier keys like SHIFT

Examples

Example 1: Filter the digitation in a form field through a regular expression

The following example shows the use of the onkeypress event during a digitation into a form field in order to filter the typed characters:

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Example</title>
<script>
  function numbersOnly(oToCheckField, oKeyEvent) {
    return oKeyEvent.charCode === 0 || /\d/.test(String.fromCharCode(oKeyEvent.charCode));
  }
</script>
</head>

<body>
<form name="myForm">
<p>Enter numbers only: <input type="text" name="myInput" onkeypress="return numbersOnly(this, event);" onpaste="return false;" /></p>
</form>
</body>
</html>

Example 2: Capture the digitation of a hidden word

The following example will do something after the user digits the word "exit" in any point of a page.

/* Type the word "exit" in any point of your page... */

(function () {

  var sSecret = /* chose your hidden word...: */ "exit", nOffset = 0;

  document.onkeypress = function (oPEvt) {
    var oEvent = oPEvt || window.event, nChr = oEvent.charCode, sNodeType = oEvent.target.nodeName.toUpperCase();
    if (nChr === 0 || oEvent.target.contentEditable.toUpperCase() === "TRUE" || sNodeType === "TEXTAREA" || sNodeType === "INPUT" && oEvent.target.type.toUpperCase() === "TEXT") { return true; }
    if (nChr !== sSecret.charCodeAt(nOffset)) {
      nOffset = nChr === sSecret.charCodeAt(0) ? 1 : 0;
    } else if (nOffset < sSecret.length - 1) {
      nOffset++;
    } else {
      nOffset = 0;
      /* do something here... */
      alert("Yesss!!!");
      location.assign("http://developer.mozilla.org/");
    }
    return true;
  };
})();

Specifications

Specification Status Comment
WHATWG HTML Living Standard
The definition of 'onkeypress' in that specification.
Living Standard

Browser Compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support (Yes) ? ? ? ?
Feature Android Android Webview Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile Chrome for Android
Basic support ? (Yes) ? ? ? ? ? (Yes)

© 2005–2017 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onkeypress