HTML event attribute onkeypress








The onkeypress attribute event is triggered when user pressed a key.

The order of events related to the onkeydown event:

  • onkeydown
  • onkeypress
  • onkeyup




What's new in HTML5

None.

Syntax

<element onkeypress="script">

Supported Tags

All HTML elements, EXCEPT:

<base>, 
<bdo>, 
<br>, 
<head>, 
<html>, 
<iframe>, 
<meta>, 
<param>, 
<script>, 
<style>, 
<title>




Browser compatibility

onkeypress Yes Yes Yes Yes Yes

Example

<!DOCTYPE html>
<html>
<body>
<!--  w  ww.j  a v  a2  s.c o  m-->
<input type="text" onkeypress="myFunction()">

<script>
function myFunction() {
    console.log("pressed a key");
}
</script>

</body>
</html>

Click to view the demo

Example 2

The following code shows how to listen to key press event for TextArea.

<html>
<head>
<script type="text/javascript">
  function handleEvent(oEvent) {<!-- ww  w  .  j a  v  a  2 s. c  o  m-->
    var oTextbox = document.getElementById("txt1");
    oTextbox.value += "\n>" + oEvent.type;
  }
</script>
</head>
<body>
  <P>Type some characters into the first textbox.</p>
  <P>
    <textarea id="txtInput" rows="15" cols="50"
      onkeydown="handleEvent(event)" onkeyup="handleEvent(event)"
      onkeypress="handleEvent(event)"></textarea>
  </p>
  <P>
    <textarea id="txt1" rows="15" cols="50"></textarea>
  </p>
</body>
</html>

Click to view the demo