How to Check if Enter Key is Pressed in Textbox JavaScript/jQuery ?
Last Updated :
07 Oct, 2024
Given a textarea element, the task is to check the user presses the enter key with the help of JQuery.
jQuery keyup() Method
This method triggers the keyup event or adds a function to run when a keyup event occurs. The keyup event occurs when a keyboard key is released.
Syntax:
Trigger the keyup event for the selected elements:
$(selector).keyup()
Attach a function to the keyup event:
$(selector).keyup(function)
jQuery trigger() Method
This method triggers the defined event and the default behavior of an event for the selected elements.
Syntax:
$(selector).trigger(event, eventObj, param1, param2, ...)
jQuery on() Method
This method adds one or more event handlers for the selected elements and child elements.
Syntax:
$(selector).on(event, childSelector, data, function, map)
Example 1: In this example, the keyup event is added to the textarea, when it occurs then a new event enterKey is triggered by keyup event.
html
<!DOCTYPE HTML>
<html>
<head>
<title>
Event for user pressing enter
button in a textbox
</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 id="h" style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 15px; font-weight: bold;">
click the Enter Key inside the textarea.
</p>
<textarea></textarea>
<br>
<p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;">
</p>
<script>
$('textarea').keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
$('textarea').on("enterKey", function (e) {
$("#GFG_DOWN").text("Enter key pressed inside textarea");
});
</script>
</body>
</html>
Output:
Example 2: In this example, the keyup event is added to the textarea, when it occurs then a message-Enter key pressed inside textarea is printed on the screen without triggering a new event to handle it.
html
<!DOCTYPE HTML>
<html>
<head>
<title>
Check enter key pressed in a
textbox using JavaScript
</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 id="h" style="color:green;">
GeeksForGeeks
</h1>
<p id="GFG_UP" style="font-size: 15px; font-weight: bold;">
click the Enter Key inside the textarea.
</p>
<textarea></textarea>
<br>
<p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;">
</p>
<script>
$('textarea').keyup(function (e) {
if (e.keyCode == 13) {
$("#GFG_DOWN").text("Enter key pressed inside textarea");
}
});
</script>
</body>
</html>
Output:
Explore
JavaScript Basics
Array & String
Function & Object
OOP
Asynchronous JavaScript
Exception Handling
DOM
Advanced Topics