Skip to content

JavaScript keypress enter | Detect the Enter key example

  • by

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:

JavaScript keypress enter

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:

Detect the Enter key example

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading