How to Check if an Enter Key is Pressed with jQuery
Read this tutorial and learn the right method of detecting whether the user pressed the Enter key. The given method provides a cross browser compatibility.
If you want to check whether the user presses the Enter key on the keyboard, you can use the <kbd class="highlighted">keydown</kbd> event.
The Enter key is widely supported across all major browsers. Attach the <kbd class="highlighted">keydown</kbd> event to the document for checking whether the key is pressed on the page:
Javascript jQuery check if an enter key is pressed
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script src="https://code.jquery.com/jquery-3.5.0.min.js">
</script>
</head>
<body>
<h1>Check if an Enter Key is Pressed with jQuery</h1>
<label>TextBox : </label>
<input id="textbox" type="text" size="40" />
<script>
$(document).on('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault();
alert('You pressed the "Enter" key');
}
});
</script>
</body>
</html>You can also use event.key === 'Enter' instead of checking numeric codes. Using event.key is the modern standard and provides reliable cross-browser compatibility.
The keydown Event
The keydown event binds an event handler to the "keydown" JavaScript event or triggers that event on an element. The keydown event is sent to the element when the browser registers a key press. The keydown event handler can be bound to any element, but the event is only sent to the element which has the focus.
The event.key Property
The event.key property indicates the specific key that was pressed. It is the modern standard for detecting keyboard input and provides reliable cross-browser compatibility.