Ctrl+Enter jQuery in TEXTAREA

2019-01-21 03:50发布

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

8条回答
仙女界的扛把子
2楼-- · 2019-01-21 04:07

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

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

link to js fiddle

查看更多
甜甜的少女心
3楼-- · 2019-01-21 04:08

first you have to set a flag when Ctrl is pressed, do this onkeydown. then you have to check the keydown of enter. unset the flag when you see a keyup for Ctrl.

查看更多
唯我独甜
4楼-- · 2019-01-21 04:15

Universal solution

Supports OS X as well.

if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
    // do something
}
查看更多
做个烂人
5楼-- · 2019-01-21 04:16

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');
        }
    });
});
查看更多
Deceive 欺骗
6楼-- · 2019-01-21 04:17
$('my_text_area').focus(function{ set_focus_flag });

//ctrl on key down set flag

//enter on key down = check focus flag, check ctrl flag
查看更多
放荡不羁爱自由
7楼-- · 2019-01-21 04:22

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)

查看更多
登录 后发表回答