How to detect pressing Enter on keyboard using jQuery?

后端 未结 18 2229
有刺的猬
有刺的猬 2020-11-22 11:07

I would like to detect whether the user has pressed Enter using jQuery.

How is this possible? Does it require a plugin?

EDIT: It looks like I need

相关标签:
18条回答
  • 2020-11-22 11:39

    A minor extension of Andrea's answer above makes the helper method more useful when you may also want to capture modified enter presses (i.e. ctrl-enter or shift-enter). For example, this variant allows binding like:

    $('textarea').enterKey(function() {$(this).closest('form').submit(); }, 'ctrl')
    

    to submit a form when the user presses ctrl-enter with focus on that form's textarea.

    $.fn.enterKey = function (fnc, mod) {
        return this.each(function () {
            $(this).keypress(function (ev) {
                var keycode = (ev.keyCode ? ev.keyCode : ev.which);
                if ((keycode == '13' || keycode == '10') && (!mod || ev[mod + 'Key'])) {
                    fnc.call(this, ev);
                }
            })
        })
    }
    

    (see also Ctrl+Enter jQuery in TEXTAREA)

    0 讨论(0)
  • Use event.key and modern JS!

    $(document).keypress(function(event) {
        if (event.key === "Enter") {
            // Do something
        }
    });
    

    or without jQuery:

    document.addEventListener("keypress", function onEvent(event) {
        if (event.key === "Enter") {
            // Do something better
        }
    });
    

    Mozilla Docs

    Supported Browsers

    0 讨论(0)
  • 2020-11-22 11:43

    There's a keypress() event method. The Enter key's ascii number is 13 and is not dependent on which browser is being used.

    0 讨论(0)
  • 2020-11-22 11:43
    $(document).keyup(function(e) {
        if(e.key === 'Enter') {
            //Do the stuff
        }
    });
    
    0 讨论(0)
  • 2020-11-22 11:47
    $(document).keydown(function (event) {
          //proper indentiation of keycode and which to be equal to 13.
        if ( (event.keyCode || event.which) === 13) {
            // Cancel the default action, if needed
            event.preventDefault();
            //call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
            $("#btnsearch").trigger('click');
        }
    });
    
    0 讨论(0)
  • 2020-11-22 11:49

    I found this to be more cross-browser compatible:

    $(document).keypress(function(event) {
        var keycode = event.keyCode || event.which;
        if(keycode == '13') {
            alert('You pressed a "enter" key in somewhere');    
        }
    });
    
    0 讨论(0)
提交回复
热议问题