Javascript DOM onkeypress Event

Introduction

Execute a JavaScript when a user presses a key:

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

View in separate window

<!DOCTYPE html>
<html>
<body>
<input type="text" onkeypress="myFunction()">

<p id="demo"></p>
<script>
function myFunction() {//from w  w w  .j a v a 2s . co m
  document.getElementById("demo").innerHTML = "You pressed a key inside the input field";
}
</script>

</body>
</html>

The onkeypress event occurs when the user presses a key (on the keyboard).

The order of events related to the onkeypress event:

The onkeypress event is not fired for all keys (e.g. ALT, CTRL, SHIFT, ESC) in all browsers.

To detect only whether the user has pressed a key, use the onkeydown event instead.

Bubbles:
Cancelable:
Event type:
Supported HTML tags:












Yes
Yes
KeyboardEvent
All HTML elements,
EXCEPT:
<base>,
<bdo>,
<br>,
<head>,
<html>,
<iframe>,
<meta>,
<param>,
<script>,
<style>, and
<title>



PreviousNext

Related