Learn to detect ENTER key example in jQuery. This is common sense that if you have to detect a key pressed in browser then you must check in keycode (ascii) value. Simple and easy. The problem arises when you don’t know how to correctly use this functionality. e.g. whether you need to bind keypress or keydown? What is ascii value of ENTER key?
1. jQuery detect ENTER key
Note that the “ENTER” key is represented by ascii code “13”. Check this ASCII charts.
To check whether user pressed ENTER key on webpage or on any input element, you can bind keypress or keydown event to that element or document object itself. Then in bind()
function check the keycode of pressed key whether it’s value is 13 is not.
If ascii code of key pressed is 13 then “ENTER” key was pressed; otherwise some other key was pressed.
2. jQuery detect ENTER key pressed on text box
$('#someTextBox').keypress(function(event){ var keycode = (event.keyCode ? event.keyCode : event.which); if(keycode == '13'){ alert('You pressed a "enter" key in textbox'); } });
3. jQuery detect ENTER key pressed on document object
$(document).keypress(function(event){ var keycode = (event.keyCode ? event.keyCode : event.which); if(keycode == '13'){ alert('You pressed a "enter" key in somewhere'); } });
event.keyCode
and event.which
.4. jQuery detect ENTER key – Try yourself
<html> <head> <script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script> </head> <body> <h1>Detect ENTER key with jQuery</h1> <label>TextBox Area: </label> <input id="someTextBox" type="text" size="40" /> <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'); } //Stop the event from propogation to other handlers //If this line will be removed, then keypress event handler attached //at document level will also be triggered event.stopPropagation(); }); //Bind keypress event to document $(document).keypress(function(event){ var keycode = (event.keyCode ? event.keyCode : event.which); if(keycode == '13'){ alert('You pressed a "enter" key in somewhere'); } }); </script> </body> </html>
Happy Learning !!
Leave a Reply