HTML onkeypress Attribute

Beginner
6 min read
Updated: Oct 2026
3 examples
Live preview

Definition and Usage

The onkeypress attribute is an inline event handler for the keypress event. It historically ran when a letter, number, punctuation, symbol, or Enter was pressed on a focused element (for example an <input>).

Modifier-only keys such as Alt, Shift, Ctrl, Meta, and Esc alone do not fire keypress. For new work, prefer onkeydown, oninput, or onbeforeinput.

Deprecated.

MDN marks the keypress event deprecated. Browsers may still fire it for compatibility — do not build new features on onkeypress.

HTML Syntax

syntax.html
<element onkeypress=" script">

script is JavaScript that runs when keypress fires. Pass event to read event.key. Modern equivalent: element.addEventListener("keydown", handler) or "input".

Attribute Values

The attribute value is a script. Common legacy patterns:

ValueDescriptionTry it
handler()Call a named function when a character key is pressedTry it
handler(event)Pass the KeyboardEvent to read event.key / event.codeTry it
Filter with preventDefault()Legacy pattern to block certain characters as they are typedTry it
Modern: oninput / onkeydownPreferred replacements for new projectsTry it

Live Preview

Focus the field and type. Printable keys update the log via legacy keypress. Try Escape or arrow keys — they usually skip keypress.

mode

Legacy demo for study. Prefer keydown or input in real apps.

Input

Last keypress: (none)

HTML Examples

Short study snippets. Use Try It Yourself for a live editor. Ship modern events in production.

Example 1 — Log Character Keys

Show which printable key fired keypress using event.key.

HTML
<label for="sample">Focus and type:</label>
<input type="text" id="sample" onkeypress="logKey(event)">
<p id="log">Waiting…</p>

<script>
  function logKey(e) {
    document.getElementById("log").textContent = "Key: " + e.key;
  }
</script>
Try It Yourself

How It Works

  1. Focus the input. Keyboard events go to the focused element.
  2. Press a character key. Letters, digits, and symbols typically fire keypress.
  3. Read event.key. Prefer it over deprecated keyCode.
  4. Study only. New code should listen for keydown or input instead.

Example 2 — Legacy Alphanumeric Filter

Old tutorials blocked symbols with preventDefault() inside onkeypress.

HTML
<label for="username">Username (letters/numbers):</label>
<input type="text" id="username" onkeypress="filterAlpha(event)">

<script>
  function filterAlpha(e) {
    if (e.key.length === 1 && !/^[a-z0-9]$/i.test(e.key)) {
      e.preventDefault();
    }
  }
</script>
Try It Yourself

How It Works

  1. Test the character. Single-character e.key values are what typing produces.
  2. Allow a–z and 0–9. Anything else that is one character is cancelled.
  3. preventDefault stops that character from entering the field.
  4. Gap: paste and autofill skip keypress — use oninput or pattern for real validation.

Example 3 — Modern Replacement with oninput

Validate the whole value after any change — typing, paste, or autofill.

HTML
<label for="username">Username:</label>
<input type="text" id="username" pattern="[A-Za-z0-9]*" title="Letters and numbers only">

<script>
  var field = document.getElementById("username");
  field.addEventListener("input", function () {
    field.value = field.value.replace(/[^a-z0-9]/gi, "");
  });
</script>
Try It Yourself

How It Works

  1. Listen to input. Fires whenever the value changes, including paste.
  2. Clean the string. Strip disallowed characters from field.value.
  3. Add pattern. Native constraint validation helps forms and assistive tech.
  4. Prefer this path. Keep onkeypress only when reading older tutorials or codebases.

Edge Cases & Pitfalls

Most surprises come from treating keypress like a complete keyboard API.

deprecated

Do not start new features on it

Specs and MDN recommend keydown or beforeinput/input. Compatibility firing can still change.

keys

Not every key fires keypress

Escape, arrows, and many modifiers usually skip it. Shortcuts belong on onkeydown.

paste

Paste bypasses character filters

Blocking keys does not clean pasted text. Sanitize on input and validate on the server.

legacy API

Avoid keyCode / which

Use event.key (character or named key) and event.code (physical key) instead.

a11y

Do not trap Tab or Escape

Never use keyboard handlers to break focus order. Prefer HTML constraints and clear error text when blocking input.

Browser Support

onkeypress is a legacy HTML event handler. Engines may still fire keypress for old pages.

✓ Deprecated · Legacy compatibility

onkeypress

Still widely recognized for printable keys, but deprecated. Prefer keydown / input for new projects. Behavior for non-character keys was never consistent.

Legacy Not for new work
Google Chrome Fires for compatibility
Deprecated*
Mozilla Firefox Fires for compatibility
Deprecated*
Apple Safari Fires for compatibility
Deprecated*
Microsoft Edge Fires for compatibility
Deprecated*
Opera Fires for compatibility
Deprecated*
Samsung Internet Fires for compatibility
Deprecated*
Internet Explorer Legacy support
Legacy*
onkeypress Deprecated — use keydown/input

Bottom line: *Learn onkeypress for old code. Build new keyboard and input logic with onkeydown, onkeyup, or oninput.

Key Takeaways

  • Role: legacy inline handler for character-oriented keypress events.
  • Status: deprecated — recognize it, do not start new features on it.
  • Replace with: onkeydown for keys/shortcuts, oninput for value changes.
  • API: use event.key, not keyCode.

One line: study onkeypress for legacy pages — write keydown / input for new ones.

Frequently Asked Questions

It is an inline event handler for the keypress event. Historically it ran when a printable character key (or Enter) was pressed in a focused element. The keypress event is deprecated.
Yes. MDN and modern specs deprecate keypress. Prefer onkeydown, beforeinput, or oninput for new projects. Learn onkeypress to read legacy code.
onkeydown fires for almost every key, including Escape and arrows. onkeypress mainly targeted character keys and is deprecated. Use onkeydown with event.key for reliable keyboard handling.
Usually no. Modifier-only keys and most navigation keys do not fire keypress. Use onkeydown for those.
No. Paste does not go through keypress. Validate the field value with oninput, or use pattern and server checks.
Use event.key (and event.code when you need the physical key). keyCode and which are deprecated.

Next: onkeyup

Handle the moment a key is released after press.

onkeyup tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful