[javascript] JQuery Event for user pressing enter in a textbox?

Is there any event in Jquery that's triggered only if the user hits the enter button in a textbox? Or any plugin that can be added to include this? If not, how would I write a quick plugin that would do this?

This question is related to javascript jquery jquery-events

The answer is


Another subtle variation. I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:

(function($) { $.fn.catchEnter = function(sel) {  
    return this.each(function() { 
        $(this).on('keyup',sel,function(e){
            if(e.keyCode == 13)
              $(this).trigger("enterkey");
        })
    });  
};
})(jQuery);

And then in use:

$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });

This variation allows you to use event delegation (to bind to elements you haven't created yet).

$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });

If your input is search, you also can use on 'search' event. Example

<input type="search" placeholder="Search" id="searchTextBox">

.

$("#searchPostTextBox").on('search', function () {
    alert("search value: "+$(this).val());
});

heres a jquery plugin to do that

(function($) {
    $.fn.onEnter = function(func) {
        this.bind('keypress', function(e) {
            if (e.keyCode == 13) func.apply(this, [e]);    
        });               
        return this; 
     };
})(jQuery);

to use it, include the code and set it up like this:

$( function () {
    console.log($("input"));
    $("input").onEnter( function() {
        $(this).val("Enter key pressed");                
    });
});

jsfiddle of it here http://jsfiddle.net/VrwgP/30/


Here is a plugin for you: (Fiddle: http://jsfiddle.net/maniator/CjrJ7/)

$.fn.pressEnter = function(fn) {  

    return this.each(function() {  
        $(this).bind('enterPress', fn);
        $(this).keyup(function(e){
            if(e.keyCode == 13)
            {
              $(this).trigger("enterPress");
            }
        })
    });  
 }; 

//use it:
$('textarea').pressEnter(function(){alert('here')})

HTML Code:-

<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />      

<input type="button" id="btnclick">

Java Script Code

function AddKeyPress(e) { 
        // look for window.event in case event isn't passed in
        e = e || window.event;
        if (e.keyCode == 13) {
            document.getElementById('btnEmail').click();
            return false;
        }
        return true;
    }

Your Form do not have Default Submit Button


I could not get the keypress event to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:

"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)

I had to use the keyup or keydown event to catch a press of the enter button.


It should be well noted that the use of live() in jQuery has been deprecated since version 1.7 and has been removed in jQuery 1.9. Instead, the use of on() is recommended.

I would highly suggest the following methodology for binding, as it solves the following potential challenges:

  1. By binding the event onto document.body and passing $selector as the second argument to on(), elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body rather than $selector directly, which means $selector can be added, removed and added again and will never load the event bound to it.
  2. By calling off() before on(), this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.
  3. By wrapping the script within $(function() {...}), this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready() does not get fired for AJAX requests, while $(function() {...}) does.

Here is an example:

<!DOCTYPE html>
  <head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
      $(function() {
        var $selector = $('textarea');

        // Prevent double-binding
        // (only a potential issue if script is loaded through AJAX)
        $(document.body).off('keyup', $selector);

        // Bind to keyup events on the $selector.
        $(document.body).on('keyup', $selector, function(event) {
          if(event.keyCode == 13) { // 13 = Enter Key
            alert('enter key pressed.');
          }
        });
      });
    </script>
  </head>
  <body>

  </body>
</html>

   $('#textbox').on('keypress', function (e) {
         if(e.which === 13){

            //Disable textbox to prevent multiple submit
            $(this).attr("disabled", "disabled");

            //Do Stuff, submit, etc..

            //Enable the textbox again if needed.
            $(this).removeAttr("disabled");
         }
   });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-events

Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function Detect Close windows event by jQuery How to bind Events on Ajax loaded Content? Get clicked element using jQuery on event? jQuery click events firing multiple times jQuery.click() vs onClick Bootstrap onClick button event Difference between $(this) and event.target? Getting the class of the element that fired an event using JQuery Attaching click event to a JQuery object not yet added to the DOM