Ctrl+Enter jQuery in TEXTAREA

前端 未结 8 616
死守一世寂寞
死守一世寂寞 2020-12-12 13:59

How do I trigger something when the cursor is within TEXTAREA and Ctrl+Enter is pressed? Using jQuery. Thanks

相关标签:
8条回答
  • 2020-12-12 14:35

    Universal solution

    This supports macOS as well: both Ctrl+Enter and ⌘ Command+Enter will be accepted.

    if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
        // do something
    }
    
    0 讨论(0)
  • 2020-12-12 14:41

    Actually this one does the trick and works in all browsers:

    if ((event.keyCode == 10 || event.keyCode == 13) && event.ctrlKey)
    

    link to js fiddle.

    Notes:

    • In Chrome on Windows and Linux, enter would be registered as keyCode 10, not 13 (bug report). So we need to check for either.
    • ctrlKey is control on Windows, Linux and macOS (not command). See also metaKey.
    0 讨论(0)
  • 2020-12-12 14:48

    I found answers of others either incomplete or not cross-browser compatible.

    This code works google chrome.

    $(function ()
    {
        $(document).on("keydown", "#textareaId", function(e)
        {
            if ((e.keyCode == 10 || e.keyCode == 13) && e.ctrlKey)
            {
                alert('ctrl+enter');
            }
        });
    });
    
    0 讨论(0)
  • 2020-12-12 14:53
    $('my_text_area').focus(function{ set_focus_flag });
    
    //ctrl on key down set flag
    
    //enter on key down = check focus flag, check ctrl flag
    
    0 讨论(0)
  • 2020-12-12 14:54

    This can be extended to a simple-but-flexible JQuery plugin as in:

    $.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);
                }
            })
        })
    }
    

    Thus

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

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

    (With thanks to https://stackoverflow.com/a/9964945/1017546)

    0 讨论(0)
  • 2020-12-12 14:54

    Maybe a little late to the game, but here is what I use. It will also force submit of the form that is the current target of the cursor.

    $(document.body).keypress(function (e) {
        var $el = $(e.target);
        if (e.ctrlKey && e.keyCode == 10) {
            $el.parents('form').submit();
        } else if (e.ctrlKey && e.keyCode == 13) {
            $el.parents('form').submit();
        }
    });
    
    0 讨论(0)
提交回复
热议问题