jQuery Detect ENTER key pressed

jQuery detect enter key pressed; Through this tutorial, i am going to show you how to detect enter key press in jQuery using keypress() event method.

jQuery Detect ENTER key pressed using keypress()

The Jquery Keypress () event occurs when the keyboard button is pressed. This keypress event is similar to the keydown event (). The keypress() method is executed with functions, when a keypress() event occurs.

Syntax jQuery KeyPress() Event Method

$(selector).keypress() 

This triggers the keypress event for the selected elements.

$(selector).keypress(function)  

Parameters of jQuery keypress() Method

ParameterDescription
FunctionIt is an optional parameter. It is executed itself when the keypress event is triggered.

Example 1 – jQuery Detect ENTER key pressed using keypress()

<!DOCTYPE html>  
<html>  
<head>  
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>  
i = 0;  
$(document).ready(function(){  
    $("input").keypress(function(){  
        $("span").text (i += 1);  
    });  
});  
</script>  
</head>  
<body>  
Enter something: <input type="text">  
<p>Keypresses val count: <span>0</span></p>  
</body>  
</html>  

Demo 1 – jQuery Detect ENTER key pressed using keypress()


Enter something:

Keypresses val count: 0


Example 2 – jQuery Detect ENTER key pressed using keypress()

To check whether the user has pressed the ENTER key on the webpage or on an input element, you can tie a keyup or keydown event to that element or document object.

If the code of the key pressed code is 13 then the “ENTER” key was pressed; Otherwise some other key was pressed.

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
    <h1>Write something here & press enter</h1>
    <label>TextBox Area: </label>
    <input id="someTextBox" type="text" size="100" />
    <script type="text/javascript">
        //Bind keypress event to textbox
        $('#someTextBox').keypress(function(event){
            var keycode = (event.keyCode ? event.keyCode : event.which);
            if(keycode == '13'){
                alert('You pressed a "enter" key in textbox'); 
            }
            event.stopPropagation();
        });
    </script>
</body>
</html>

Demo 2 – jQuery Detect ENTER key pressed using keypress()


Write something here & press enter

Recommended jQuery Tutorial

Be First to Comment

Leave a Reply

Your email address will not be published.