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

  • onkeypress fires for printable characters only (not for Ctrl, Alt, etc.)
  • Use onkeydown for 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.

Updated on: 2026-03-15T23:18:59+05:30

445 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements