Search.../

onKeyPress( )

Adds an event handler that runs when the cursor is inside the input element and a key is pressed.

Description

A text input receives a keyPress event when a user presses a key on the keyboard while the cursor is inside the input element. A keyPress event is fired for printable and non-printable characters.

You can also define an event handler using the Properties and Events panel.

Notes:

  • Some browsers do not issue a key press event for certain keys, such as arrow keys or the shift key.

  • When you retrieve the value from the target property of a KeyboardEvent, you get the value of the target element before the key was pressed.

Syntax

function onKeyPress(eventHandler: KeyboardEventHandler): Element
eventHandler: function KeyboardEventHandler(event: KeyboardEvent): void

onKeyPress Parameters

NAME
TYPE
DESCRIPTION
eventHandler

The name of the function or the function expression to run when a key is pressed.

Returns

The element on which the event is now registered.

Return Type:

KeyboardEventHandler Parameters

NAME
TYPE
DESCRIPTION
event

The keyboard event that occurred.

Returns

This function does not return anything.

Return Type:

void
Mixed in from:$w.TextInputMixin

Was this helpful?

Get the key that was pressed

Copy Code
1$w("myElement").onKeyPress( (event) => {
2 let key = event.key; // "a"
3} );
Get all of the keyboard event's properties

Copy Code
1$w("#myElement").onKeyPress( (event) => {
2 let key = event.key; // "A"
3 let shift = event.shiftKey; // true
4 let meta = event.metaKey; // false
5 let alt = event.altKey; // false
6 let ctrl = event.ctrlKey; // false
7 let value = event.target.value; // string value of text inside "#myElement" before the last KeyPress event
8} );