HTML onkeypress Attribute

HTML onkeypress Attribute: This attribute can be defined as it fires whenever the user presses a key on the keyboard. And this event attribute can not be used for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers. And also the onkeydown attribute works for all keys in all browsers. The script will be run when onkeypress attribute call.

HTML onkeypress Attribute

This attribute can be applied to all the HTML elements. And the order of events that are related to the onkeypress events are as follows:

  • onkeydown
  • onkeypress
  • onkeyup

Syntax: <element onkeypress=”script”>

Browser Support

This attribute is supported by the following browsers:

  • Chrome
  • Safari
  • Opera
  • Internet Explorer
  • Firefox

Example: for <input> element

<!DOCTYPE html>
<html>
<body>

<p>A function is triggered when the user is presses a key.</p>

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

<script>
function myFunction() {
  alert("You pressed a key inside the input field");
}
</script>

</body>
</html>

Output:

A function is triggered when the user is pressing a key in the input field.