Check if an Enter Key Is Pressed With jQuery


/ Published in: jQuery
Save to your folder(s)

To check if an “enter” key is pressed inside a textbox, just bind the keypress() to the textbox.


Copy this code and paste it in your HTML
  1. <html>
  2. <head>
  3.  
  4. <script type="text/javascript" src="jquery-1.4.2.min.js"></script>
  5.  
  6. </head>
  7. <body>
  8. <h1>Check if "enter" is pressed with jQuery</h1>
  9.  
  10. <label>TextBox : </label>
  11. <input id="textbox" type="text" size="50" />
  12.  
  13. <script type="text/javascript">
  14.  
  15. $('#textbox').keypress(function(event){
  16.  
  17. var keycode = (event.keyCode ? event.keyCode : event.which);
  18. if(keycode == '13'){
  19. alert('You pressed a "enter" key in textbox');
  20. }
  21. event.stopPropagation();
  22. });
  23.  
  24. $(document).keypress(function(event){
  25.  
  26. var keycode = (event.keyCode ? event.keyCode : event.which);
  27. if(keycode == '13'){
  28. alert('You pressed a "enter" key in somewhere');
  29. }
  30.  
  31. });
  32.  
  33. </script>
  34. </body>
  35. </html>

URL: http://simply-tutorial.com/blog/2010/05/17/how-to-check-if-an-enter-key-is-pressed-with-jquery/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.