Enter key keycode is 13. Using a keydown event can catch a user pressed enter key or not.
Detect keypress enter in JavaScript
HTML example code capture Enter key keycode on the press by the user. Execute a code when the user presses a key on the keyboard. Match with if condition Number 13 is the “Enter” key on the keyboard.
<!DOCTYPE html>
<html>
<body>
<script>
document.addEventListener("keydown", function(event) {
if (event.which == 13) {
alert(event.which + " " + event.key);
}
});
</script>
</body>
</html>
Output:
Q: How to Detect the Enter key in a text input field?
Answer: If you want to have an event on the input field then you need to make sure handle()
will return false, otherwise the form will get submitted.
<form action="#">
<input type="text" name="txt" onkeypress="handle(event)" />
</form>
<script>
function handle(e){
if(e.keyCode === 13){
e.preventDefault(); // Ensure it is only this code that runs
alert("Enter was pressed was presses");
}
}
</script>
Output:
Do comment if you have any doubts or suggestions on this JS event code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version