jQuery Keypress enter example

In this post, we will see how to detect if enter key is pressed or not in jQuery.

To capture enter keypress, we will bind dom element with keypress event and if ascii value is 13, then enter key is pressed.

So basically code will look something like this.
$('#textBox').keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        alert('You pressed a "enter" key in textbox');  
    }
});
If you want to catch keypress event in whole web page, you can simply use:
$('#document').keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        alert('You pressed a "enter" key in textbox');  
    }
});

JQuery keypress enter example:

<html>
<head>
 
<script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
 
</head>
<body>
  <h1>Detect if Enter key is pressed</h1>
 
<label>TextBox : </label>
<input id="textbox" type="text" size="40" />
 
<script type="text/javascript">
 
$('#textbox').keypress(function(event){
 
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
        alert('You pressed a "enter" key in textbox');  
    }

});

</script>
</body>
</html>

Output:


Live demo: jQuery keypress enter example

Written by Arpit:

If you have read the post and liked it. Please connect with me on Facebook | Twitter | Google Plus

 

Java tutorial for beginners Copyright © 2012