ChatGPT解决这个技术问题 Extra ChatGPT

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?


J
Jishnu A P

You can wire up your own custom event

$('textarea').bind("enterKey",function(e){
   //do stuff here
});
$('textarea').keyup(function(e){
    if(e.keyCode == 13)
    {
        $(this).trigger("enterKey");
    }
});

http://jsfiddle.net/x7HVQ/


It's worth noting that in a scenario of enter detection to prevent form submission, "keyup" event is not optimal because the form detects the submit on keydown. Thus "keydown" or "keypress" might be better in that case.
Note, bind() is deprecated in jQuery 3.0.
Different browsers has different e.keyCode for some keys, better to use e.which, this will guarantee that you will handle same button on every browser
E
Etienne Dupuis
   $('#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");
         }
   });

Thanks - This solution fitted my use case. However, it's worth noting that once any processing is done, you may want to add ` $(this).removeAttr("disabled");` to re-enable the textbox.
N
Naftali

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')})

Nice. Much simpler than that URL I posted. I wonder what the heck the article I posted is all about & why it takes so much code..
Too late, I've already written my own :P. It also does the same job in less lines.. also, using the $ variable for the plugin isn't a good idea as it can cause conflicts.
@Neal, do you know how the code of the plugin I posted in the accepted answer would have to be changed, so that one could do $("#myInput").bind('click, onEnter', myCallback); and it would work without needing anything else?
@ClickUpvote #1: remove it from the answer -- then we can talk.
@Neal Amazing solution man. I just had copy that function! thanks!
j
jzilla

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/


Nice, I'd call the callback using func.apply(this), that way inside the callback function you can use this as normal to access the element on which the event was triggered.
yeah, good point about func.apply(this), had not even considered that.
Nice and concise, but I'd add that stopping propagation and defaults would be a good idea in most cases, to prevent any form submission. Just add e.preventDefault(); e.stopPropagation(); inside the if (e.keyCode) bit.
J
Joshua Burns

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:

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. 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. 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>

L
Linh

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());
});

y
yogesh lodha

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


W
Wilco

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 */ });

Z
Zeeshan Liaqat

//Short and simple solution

$(document).ready(function(){

$('#TextboxId').keydown(function(event){
    if (event.which == 13){
       //body or action to be performed
    }
});

});

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
A
Arne M

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.