<textarea onKeyPress="">
Disclosure: Your support helps keep the site running! We earn a referral fee for some of the services we recommend on this page. Learn more
- Attribute of
- HTML5 Textarea Attributes: Here's What You Should Know
- What does
<textarea onKeyPress="">
do? - Adds an event listener to a <textarea> element which executes JavaScript scripting when an onKeyPress event occurs.
Code Example
<form>
<textarea
onkeypress="alert('You triggered the onkeypress event.')"
placeholder="Place your cursor in this textarea and press a key.">
</textarea>
</form>
Taking Action as Soon as a Key is Pressed
The onkeypress
event is used to trigger the execution of JavaScript as soon as any character key is pressed while the textarea
is selected.
This event is very similar to onkeydown
and onkeyup
which also listen for key presses. The difference is that onkeypress
only listens for keys that represent typed characters while the others listen for all keypress events. So, tab, ctrl, and shift won’t trigger the onkeypress
event, but they will trigger the onkeydown
and onkeyup
events.
Take the following text areas for instance:
<textarea onkeypress="alert('You pressed a character key.')">
Pressing keys like Shift and Ctrl in this text area won't do anything.
</textarea>
<textarea onkeydown="alert('You pressed a key down.')">
Press any key down while this text area is selected and you'll see an alert.
</textarea>
<textarea onkeyup="alert('You pressed and released a key.')">
Press and release any key while this text area is selected and you'll see an alert.
</textarea>
Here’s how those text areas are rendered by the browser. Go ahead and play around with them to get a feeling for how they all work.