Ctrl+Enter jQuery in TEXTAREA

邮差的信 提交于 2019-11-28 15:51:30

You can use the event.ctrlKey flag to see if the Ctrl key is pressed, something like this:

$('#textareaId').keydown(function (e) {

  if (e.ctrlKey && e.keyCode == 13) {
    // Ctrl-Enter pressed
  }
});

Check the above snippet here.

Yaroslav Yakovlev

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

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

link to js fiddle

Universal solution

Supports OS X as well.

if ((e.ctrlKey || e.metaKey) && (e.keyCode == 13 || e.keyCode == 10)) {
    // do something
}

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

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)

idrumgood
$('my_text_area').focus(function{ set_focus_flag });

//ctrl on key down set flag

//enter on key down = check focus flag, check ctrl flag
mkoryak

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.

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();
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!