HTML onkeypress Event Attribute

Description

The onkeypress HTML event attribute is used to specify a JavaScript function to be executed when the user presses a key on the keyboard. It can be used on any HTML element, but it is most commonly used on input elements to validate user input.

The onkeypress event is fired when the user presses a key that produces a character value. This includes alphabetic, numeric, and punctuation keys. It does not include modifier keys such as Alt, Ctrl, Shift, or Meta.

The onkeypress event is deprecated, meaning that it is not supported by all browsers and may be removed in the future. It is recommended to use the onkeydown event instead, which is fired for all keys.

Here is an example of how to use the onkeypress event attribute:

<input type="text" onkeypress="myFunction()">

When the user presses a key in the input field, the myFunction() function will be executed. The myFunction() function could be used to validate the user input, for example, to ensure that the user only enters alphabetic characters.

Here is an example of a JavaScript function that can be used to validate user input:

function myFunction() {
  var input = document.getElementById("myInput");
  var key = event.keyCode;

  if (key < 65 || key > 90) {
    event.preventDefault();
  }
}

This function will prevent the user from entering any character that is not a letter of the alphabet.

The onkeypress event attribute can be a useful tool for validating user input and creating interactive web pages. However, it is important to note that it is deprecated and should not be used in new projects. Instead, the onkeydown event should be used.

Syntax

<element onkeypress="script">

Values

  • scriptThe name of the script to use when the event has been triggered.

Example

<!DOCTYPE html>
<html>
<head>
<title>Event Attribute onkeypress</title>
</head>
<body>
<p>Click any button in the form to run the script:</p>
<input type="text" onkeypress="keyboardTest()">
<script>
function keyboardTest() {
alert("EXAMPLE: You see this window because you triggered the script");
}
</script>
</body>
</html>

Browser Support

The following table will show you the current browser support for the HTML onkeypress Event Attribute.

Desktop
Edge Chrome Firefox Opera Safari
YesYesYesYesYes
Tablets / Mobile
Chrome Firefox Opera Safari Samsung Webview
YesYesYesYesYesYes

Last updated by CSSPortal on: 8th October 2023