JavaScript/JQuery : Detect or intercept enter key pressed example




Problem :

You created a text input box and want detect(or rather intercept) if the user pressed the enter button. You need to get the user to click on the submit button rather than pressing the enter button. How to do that?

NOTE : For some online banking websites, this method has become a requirement(by insisting the user to press the submit button). Maybe to prevent bot access or other security purpose.

Solution :

Long time ago when primitive computers were being crafted by our ancestors. Computers can only understand numbers, so some sort of code is use to represent characters such as 'a' or '@' or an action of some sort. They all agreed to stick to a standard table for interpreting each keyboard buttons. This standard table is now known as the ASCII table.

When a person type into the screen, eventually he or she will have to get to the next line starting from the left side of the screen again. This process is known as carriage-return or commonly known as hitting the "enter" button to get a new line to type in more text. From the ASCII table, the carriage-return is associated with the number 13 and JQuery will be able to detect if a carriage-return(enter key pressed) event just happened by intercepting the event.keyCode.

Ok, enough of grandpa stories, here is an example on how to detect or intercept "enter" key press.

 <html>

 <head>

 <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>

 </head>

 <body>
 <h1>Detect or intercept if "enter" key is pressed</h1>

 <label>Username : </label>
 <input id="username" type="text" size="20" />
 <input id="submit" value="submit" type="button" />

 <script type="text/javascript">

 // bind to the username text input box

 $('#username').keypress(function(event){
 
 var keycode = (event.keyCode ? event.keyCode : event.which);
 if(keycode == '13'){
 alert('Cannot press"enter" key while entering username'); 
 }
 });

 // in case the user entered the username and hit "enter" 
 // button. Bind to the main page(document)

 $(document).keypress(function(event){
 
 var keycode = (event.keyCode ? event.keyCode : event.which);
 if(keycode == '13'){
 alert('Please press "submit" button instead of the "enter" key'); 
 }
 
 });
 </script>
 </body>

 </html>

Play at CodePen or Demo





By Adam Ng

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.


Advertisement