How To Detect If Enter Key Is Pressed In A Text Input Field Using Jquery



jQuery and programming have some of the most important functions associated with triggering or activating a certain set of events and functions. Likewise, if there is an instance, which might require the user to check whether an event function is activated or not, is performed using the keypress() function.

With this function, you can simply detect a function is called to run, when a keypress event gets going. Yet, keypress() cannot be used for detecting all the keys in the keyboard, with some exceptions being alt, ctrl, esc, shift, etc. Like any other inbuilt functions in jQuery, keypress() is a parameterized operation, and a parameter can be called within the scope of the function.

Following code demonstrate how to check if the enter key is pressed in a text input field in jQuery.


<!DOCTYPE html>

<html lang="en">


<meta charset="utf-8">

<title>Detect the Enter Key in a Text Input Field with jQuery</title>

<script src=""></script>


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

        if(e.which == 13){

            var inputVal = $(this).val();

            alert("You've entered: " + inputVal);






    <p><strong>Note:</strong> Type something in the text input box and press enter key.</p>      

    <p><input type="text"></p>      



Now, taking the side of the code, the source script has the document, which takes the function help of keypress and input space with respect to function e. In the forthcoming statements, the value of e is taken and is checked whether is equal to key code number “13.” Now 13 is the code of the function combination keypress, and with the assistance of which function e is compared for any blank space.

Following the checked value, the inputVal variable is taken and the value of the function is merged with the previous check, this will ensure to give an alert, that will come up and state “you have entered: <blank space>.

Why is the function useful? The answer is the utility scope, which will allow the user to get more space and not to give unnecessary blank space in every application. The usage of ASCII codes comes to the savior and makes easy out amends for coding simplicity. Likewise, in the program code above, the usage of ASCII values have ensured the blank space, formed as for pressing enter key is easily rectified.

Almost all of the up-to-date OOP supported programming languages are today, equipped, contains packages of both functions, and accepts ASCII values, which is considered the global search code. The entire set of codes contains numerous utilities and data input values embedded with different values.

View Demo

↑ Back to Top