Ctrl+Enter jQuery in TEXTAREA

前端 未结 8 635
死守一世寂寞
死守一世寂寞 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: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)

提交回复
热议问题