Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is onkeypress event in JavaScript?
The onkeypress event in JavaScript triggers when a user presses and releases a key while an element has focus. This event is commonly used with input fields, text areas, and other interactive elements to respond to user keyboard input.
Syntax
element.onkeypress = function(event) {
// Handle keypress
};
// Or in HTML
<input onkeypress="functionName()">
Basic Example
Here's how to use the onkeypress event to detect when a key is pressed in an input field:
<html>
<head>
<script>
function sayHello() {
alert("A key is pressed.");
}
</script>
</head>
<body>
<input type="text" onkeypress="sayHello()" placeholder="Type something...">
</body>
</html>
Advanced Example with Event Object
You can access the pressed key information using the event object:
<html>
<head>
<script>
function handleKeypress(event) {
const key = event.key;
const keyCode = event.keyCode || event.which;
console.log("Key pressed: " + key);
console.log("Key code: " + keyCode);
// Example: Only allow numbers
if (keyCode < 48 || keyCode > 57) {
event.preventDefault();
alert("Only numbers allowed!");
}
}
</script>
</head>
<body>
<input type="text" onkeypress="handleKeypress(event)" placeholder="Numbers only">
</body>
</html>
Event Properties
| Property | Description | Example |
|---|---|---|
event.key |
The actual key pressed | "a", "Enter", "Space" |
event.keyCode |
Numeric code of the key | 97 for "a", 13 for Enter |
event.which |
Alternative to keyCode | Same as keyCode |
Key Points
-
onkeypressfires for printable characters only (not for Ctrl, Alt, etc.) - Use
onkeydownfor all keys including special keys - The event can be prevented using
event.preventDefault() - Modern browsers prefer
addEventListener('keypress', function)over inline handlers
Conclusion
The onkeypress event is useful for handling user keyboard input in real-time. Use it for input validation, character filtering, or triggering actions based on specific key presses.
Advertisements
