How to detect pressing Enter on keyboard | jQuery
The jQuery keydown() is an inbuilt method in jQuery which triggers the keydown event, or attaches a function to run when a keydown event occurs.
$(selector).keydown()
Example
$('#myTxt').keydown(function (e){
if(e.keyCode == 13){
alert('you pressed enter key');
}
})
The order of events related to the keydown event:
- keydown : The key is on its way down
- keypress : The key is pressed down
- keyup : The key is released
Detect ENTER key press event | jQuery

Type something and press Enter key:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#myTxt').keydown(function (e){
if(e.keyCode == 13){
alert('you pressed enter key');
}
})
});
</script>
</head>
<body>
<p>Type something and press Enter key:</p>
<input type="text" id="myTxt"/>
</body>
</html>
As the .keydown() method is just a shorthand for .on( "keydown", handler ), detaching is possible using .off( "keydown" ).
jQuery .keypress()

The keypress event is sent to an element when the browser registers keyboard input.
$('#myTxt').keypress(function (e){
if(e.keyCode == 13){
alert('you pressed enter key');
}
})
jQuery .keyup()
The keyup event is sent to an element when the user releases a key on the keyboard.
$('#myTxt').keyup(function (e){
if(e.keyCode == 13){
alert('you pressed enter key');
}
})
jQuery .keyup() event can be attached to any element, but the event is only sent to the element that has the focus.
e.keyCode == 13
ENTER key is represented by ASCII code "13". In order to check whether user pressed ENTER key on webpage or on any input element, you can bind keypress or keydown event to that element or document object itself.
if(e.keyCode == 13){
alert('you pressed enter key');
}
If ascii code of key pressed is 13 then ENTER key was pressed; otherwise some other key was pressed.
Related Topics
- How to get input textbox value using jQuery
- Get Selected Dropdown Value on Change Event | jQuery
- How to submit a form using ajax in jQuery
- How can I get the ID of an element using jQuery
- Open Bootstrap modal window on Button Click Using jQuery
- How to select an element with its name attribute | jQuery
- How to get the data-id attribute using jQuery
- How to disable/enable submit button after clicked | jQuery
- How to replace innerHTML of a div using jQuery
- Change the selected value of a drop-down list using jQuery
- How to get the value of a CheckBox with jQuery
- How to wait 'X' seconds with jQuery?
- How to allow numbers only in a Text Box using jQuery.
- How to dynamically create a div in jQuery?