CKTIS / HTML
onkeypress — keypress event handler attribute
The global HTML attribute onkeypress contains JavaScript code that handles the keypress event. The attribute name includes the on prefix; the event name does not.
Version: WHATWG HTML Living Standard; index snapshot date recorded separately
Syntax
onkeypress="JavaScript statements"onkeypress is a global event handler attribute available on HTML elements. Its value is JavaScript code, not an event name or a Boolean value. keypress is a deprecated legacy event; do not rely on it in new code.
The onkeypress attribute and the JavaScript property element.onkeypress expose the same handler mechanism for keypress. Write code in the attribute; assign a function or null to the property. The event parameter exposes the event to the executing code.
Content Security Policy can block handlers written directly in attributes. Do not insert untrusted text into their values as code.
The example dispatches keypress programmatically to show that the handler runs without manual keystrokes. The expected text is keypress; this test does not establish when a browser generates keypress during actual typing.
Examples
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>onkeypress demo</title>
<input id="field" aria-label="Text" onkeypress="document.getElementById('result').textContent = event.type">
<output id="result"></output>
<script>
document.getElementById('field').dispatchEvent(
new KeyboardEvent('keypress', { key: 'a' })
);
</script>
</html>Result
keypress
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.