HTML onkeypress Attribute

Beginner
⏱️ 6 min read
📚 Updated: Jun 2026
🎯 3 Examples
Events & Handlers

Introduction

The onkeypress attribute is an inline event handler for the keypress event — historically fired when the user presses a printable character key in a focused field. You will still see it in older tutorials and legacy code. Important: the keypress event is deprecated in modern web standards. For new projects, use onkeydown, onkeyup, or oninput instead. This page teaches onkeypress so you understand legacy markup, with clear guidance on what to use today.

What You’ll Learn

01

Event handler

Inline JS.

02

keypress event

Character keys.

03

Deprecated

Use keydown.

04

vs onkeydown

When to use.

05

event.key

Not keyCode.

06

Validation

Filter input.

Purpose of onkeypress Attribute

The original purpose of onkeypress was to react when a user typed a character — for example blocking non-alphanumeric input or counting keystrokes. It fires after keydown and before keyup for character keys in many browsers, but not for keys like Escape, arrows, or F-keys.

Today, the same goals are better achieved with oninput (value changed), pattern / inputmode HTML attributes, or onkeydown with event.key. Learn onkeypress to maintain old code; write new code with modern events.

⚠️
Deprecated event

The keypress event is deprecated. Browsers may still fire it for compatibility, but MDN and modern specs recommend keydown or input for new work.

📝 Syntax

Set onkeypress on a focusable element (legacy pattern):

onkeypress.html
<input type="text" onkeypress="myFunction(event)">

<script>
  function myFunction(e) {
    console.log("Character key:", e.key);
  }
</script>

Syntax Rules

  • Value is JavaScript executed when the keypress event fires.
  • Historically limited to character-producing keys — not reliable for all keys.
  • Pass event and use event.key — avoid legacy keyCode.
  • Use event.preventDefault() to block a character from entering the field.
  • Modern replacement: onkeydown or oninput.
  • Alternative (legacy): element.addEventListener("keypress", handler).
  • The keypress event bubbles.

💎 Values

The onkeypress attribute accepts a string of JavaScript code:

  • onkeypress="myFunction()" — Call a named function.
  • onkeypress="validateUsername(event)" — Pass the event object.
  • JavaScript: field.onkeypress = (e) => { … } assigns the handler.
modern-alternative.html
// Preferred for new code — not keypress:
username.addEventListener("keydown", (e) => {
  if (e.key.length === 1 && !/^[a-z0-9]$/i.test(e.key)) {
    e.preventDefault();
  }
});

// Or validate the whole value:
username.addEventListener("input", () => {
  username.value = username.value.replace(/[^a-z0-9]/gi, "");
});

⚡ Quick Reference

Actionkeypress fires?Modern alternative
Type letter or numberOften yesonkeydown or oninput
Press Escape / Arrow keysUsually noonkeydown
Paste textNooninput
Block invalid characterLegacy patternpattern or oninput
New project in 2026Avoidonkeydown
Handler attributeonkeypressLegacy inline handler

Applicable Elements

TargetSupported?Notes
<input type="text">Yes (legacy)Common in old tutorials
<textarea>Yes (legacy)Character input
document via scriptYes (legacy)Prefer keydown
<div> without tabindexNoNot focusable

onkeypress vs onkeydown vs oninput

HandlerStatusTypical use today
onkeypressDeprecatedRead legacy code only
onkeydownCurrentAll keys, shortcuts
oninputCurrentValue changed (incl. paste)

Examples Gallery

Alphanumeric filter (legacy style), addEventListener, and the modern keydown replacement.

👀 Live Preview

Type in the field — printable keys show below (legacy keypress demo):

Last keypress: (none)

Example — Alphanumeric username (legacy)

Block non-alphanumeric characters with onkeypress and event.key:

validate-onkeypress.html
<input type="text" id="username"
  onkeypress="validateUsername(event)">

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

How It Works

preventDefault() stops the character from appearing. This replaces old keyCode checks with readable event.key tests.

Dynamic Values with JavaScript

Attach a legacy keypress listener in script:

dynamic-onkeypress.html
<input type="text" id="dynamicField">

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

How It Works

Same registration pattern as other events — only the event name is legacy.

Example — Modern replacement with oninput

Strip invalid characters after any change (including paste):

modern-oninput.html
const username = document.getElementById("username");

username.addEventListener("input", () => {
  username.value = username.value.replace(/[^a-z0-9]/gi, "");
});
Try It Yourself

How It Works

Validate the field value, not individual key codes. Simpler and more reliable for beginners.

♿ Accessibility

  • Do not block standard keys silently — If you prevent input, show a visible error message.
  • Allow keyboard navigation — Never use keypress handlers to trap Tab or Escape.
  • Prefer HTML validationrequired, pattern, and labels work with assistive tech.
  • Announce errors — Use aria-invalid and aria-describedby on validated fields.
  • Use modern events — Screen reader and browser behavior is more predictable with input and keydown.

🧠 How onkeypress Works

1

User types character

Printable key.

Keyboard
2

keydown fires first

Then keypress (legacy).

Order
3

keypress fires

onkeypress runs.

Event
=

Legacy character hook

Use keydown/input today.

Browser Support

Browsers still fire keypress for backward compatibility, but the event is deprecated. Do not build new features on onkeypress.

⚠️ Deprecated · Still fires in browsers

Legacy onkeypress support

Works for many printable keys today, but specs and MDN recommend keydown or input instead.

90% Legacy support
Google Chrome Deprecated, still fires
Legacy
Mozilla Firefox Deprecated, still fires
Legacy
Apple Safari Deprecated, still fires
Legacy
Microsoft Edge Deprecated, still fires
Legacy
Internet Explorer Legacy support
Legacy
Opera Deprecated, still fires
Legacy
onkeypress attribute (deprecated) 90% legacy support

Bottom line: Learn it for old code; use onkeydown or oninput for new projects.

💡 Best Practices

✅ Do

  • Use onkeydown or oninput in new projects
  • Use event.key instead of deprecated keyCode
  • Validate full field values (handles paste and autofill)
  • Prefer HTML pattern and inputmode when possible
  • Read onkeypress when maintaining legacy scripts

❌ Don’t

  • Start new features with onkeypress
  • Rely on keypress for Escape, arrows, or shortcuts
  • Use keyCode / which in new code
  • Assume keypress blocks pasted invalid characters
  • Silently prevent keys without user feedback

Conclusion

The onkeypress attribute handled printable character keys in older web pages. It remains useful to recognize in legacy code, but modern development should use onkeydown, onkeyup, or oninput instead.

When you see onkeypress in a tutorial or codebase, know what it does — then reach for up-to-date events when you write your own handlers.

Key Takeaways

Knowledge Unlocked

Five truths every developer should know about onkeypress

Understand legacy keyboard events — then use modern ones.

5
Core concepts
📝 02

Characters

Not all keys.

Scope
🔄 03

Use keydown

Modern fix.

Replace
📝 04

event.key

Not keyCode.

API
✎️ 05

oninput

Full value.

Validate

❓ Frequently Asked Questions

It runs JavaScript when the deprecated keypress event fires — mainly for printable character keys in focused fields.
Yes. Use onkeydown, onkeyup, or oninput for new projects.
onkeydown fires for almost every key. onkeypress historically targeted character keys only and is deprecated.
No — use onkeydown with event.key === "Escape".
No. Use event.key in modern code. keyCode is deprecated.
Many still fire it for compatibility, but behavior may change — do not depend on it for new features.

Understand legacy keyboard events

Practice onkeypress in the editor, then compare with modern onkeydown and oninput patterns.

Try onkeypress demo →

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.

5 people found this page helpful