How to detect enter key press on keyboard with jQuery

Syntax

$(selector).keypress()

Definition and Usage

jQuery is a complete application version of Java, which like any other programming language, is particular with the keys and applications of each of them. There are specific scenarios, where a developer might be skeptical on whether he/she have assured to develop the “Enter” key properties in the code. Enter Key in any computing applications is considered the most valuable form to send and transmit data.

For the same reason, there is a very useful and a specific way, which requires the application of an ASCII Code called as key code 13. This is equivalent to Enter and most of the modern-day browsers allow the usage and application of the same.

Here is the code, which works to accept the enter key on a keyboard.

Example

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Check if Enter Key is Pressed with jQuery</title>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

    $(document).on("keypress", function(e){

        if(e.which == 13){

            $("body").append("<p>You've pressed the enter key!</p>");

        }

    });

</script>

</head>

<body>

    <p><strong>Note:</strong> Click on the viewport and press the Enter key on the keyboard. A message will be displayed.</p>

</body>

</html>

Here, we see the source code under the script menu, where the program is asking the user to input or press the enter key and the “append” function (e) is used to accept all the possible outcomes. Inside the function, e checks whether the code is equivalent to 13. If the answer of the “if” statement is affirmative, the function will once again append the enter key inside the main script body.

In the main case, the requirement of a statement or function event is required, which will then be appended to the enter key. Thus, the function box e is taken i to consideration, which works for a script called document and the function “on” is emphasized. Finally, in the end of a code, the main body of a program is appended to the print statement.

ASCII codes and its applications play a huge part in programming logic control. The usage of these codes simplifies functions and allows the programmers to manipulate just by using the appropriate codes. In Object Oriented Programming concepts, ASCII is used in every possible junctures for different keys and set of operations. Here in this case, the usage of “Enter” key plays a vital role in any application software, which will assure the user’s entry to proceed forward.

View Demo

↑ Back to Top