Ctrl + Enter using jQuery in a TEXTAREA
Asked Answered
C

10

113

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

I am using jQuery.

Concerned answered 5/11, 2009 at 22:45 Comment(1)
the answer you accepted does not work. Please change your accepted answerWolbrom
P
142

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.

Paranymph answered 5/11, 2009 at 22:55 Comment(5)
This does not work in Google Chrome. When Ctrl + Enter is pressed the key code is 10, not 13.Transmitter
This does not work. Yarolslav Yakovlev's solution below does work properly. Please change accepted answer to save people time.Exponent
@Replete Which environment have you tested? Is there any documentation about keyCode 10?Supernova
keyCode 10 shouldn't happen anymore on Chrome, see bugs.chromium.org/p/chromium/issues/detail?id=79407Alexandro
when trigger keypress event, the keycode will be 10, but keydown or keyup will report 13. Only test chromeMetallurgy
A
158

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.
Acuminate answered 18/2, 2012 at 16:52 Comment(8)
The fiddle doesn't work in Firefox 27, what's wrong?Gary
Just call add event: if ((event.keyCode == 10 || event.keyCode == 13) && event.ctrlKey)Fractional
@Yaroslav : Can you please tell what is the use of "event.keyCode == 10" in you answer.Urtication
@Urtication From the answer that is marked as the answer: This does not work in Google Chrome. When Ctrl + Enter is pressed the key code is 10, not 13Acuminate
If anyone still wondering about keyCode 10 and other chrome stuff read this.Erminia
@YaroslavYakovlev does ctrlKey correspond to the Command key on Macs?Chemoprophylaxis
That Chrome bug has long been fixed apparently, see bugs.chromium.org/p/chromium/issues/detail?id=79407Alexandro
To support Mac too: if ((e.keyCode == 10 || e.keyCode == 13) && (e.ctrlKey || e.metaKey))Rufous
P
142

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.

Paranymph answered 5/11, 2009 at 22:55 Comment(5)
This does not work in Google Chrome. When Ctrl + Enter is pressed the key code is 10, not 13.Transmitter
This does not work. Yarolslav Yakovlev's solution below does work properly. Please change accepted answer to save people time.Exponent
@Replete Which environment have you tested? Is there any documentation about keyCode 10?Supernova
keyCode 10 shouldn't happen anymore on Chrome, see bugs.chromium.org/p/chromium/issues/detail?id=79407Alexandro
when trigger keypress event, the keycode will be 10, but keydown or keyup will report 13. Only test chromeMetallurgy
T
113

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
}
Tobietobin answered 7/4, 2016 at 14:16 Comment(4)
Don't ignore this answer because it's got a lower score, it's just a newer answer, it's actually better.Goatish
Explanation of first part: On macOS, e.ctrlKey detects ⌃ Control and e.metaKey detects ⌘ Command. Use this if you want both Ctrl-Enter and Command-Enter to trigger the behavior.Netti
Can you explain why you accept a e.keyCode of 10 to mean Enter in addition to 13? The MDN keyCode documentation lists only 13 as a possible value for Enter, tested across multiple browsers and operating systems.Netti
@RoryO'Kane Some versions of Chrome on Windows and Linux use the value 10, apparently.Phosphorus
W
5

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

This code works in Google Chrome.

$(function ()
{
    $(document).on("keydown", "#textareaId", function(e)
    {
        if ((e.keyCode == 10 || e.keyCode == 13) && e.ctrlKey)
        {
            alert('Ctrl + Enter');
        }
    });
});
Worked answered 15/5, 2014 at 4:39 Comment(3)
Could you consider improving your answer by adding further explanations? Thanks :) Otherwise this would just be a low quality answer to a low quality question.Irmgard
@Worked : Can you please tell what is the use of "event.keyCode == 10" in you answer.Urtication
I love copy & paster answersPhotoemission
D
2

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 How can I detect pressing Enter on the keyboard using jQuery?)

Diwan answered 27/1, 2015 at 2:14 Comment(0)
S
2

Worth noting that keyCode has been deprecated.

You can use:

if((e.ctrlKey || e.metaKey) && e.key === "Enter")

Which works on both Mac and Windows.

Using React + TS it looks something like this:

const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
     if((e.ctrlKey || e.metaKey) && e.key === "Enter"){
         //do something
     }
};
Shebeen answered 29/5, 2023 at 8:56 Comment(0)
F
1

event.keyCode and event.which are deprecated.

The following works to handle CTRL/Command + Enter on Mac and Windows (React)

import React from "react";

export const Component = () => {
    const keyDownHandler = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
        if ((e.ctrlKey || e.metaKey) && e.key == "Enter") {
            // handle Ctrl/Command + Enter
        }
    };
    
    return (
        <textarea onKeyDown={keyDownHandler} />
    );
};
Fiertz answered 1/11, 2022 at 8:49 Comment(0)
B
0

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.

Basilius answered 5/11, 2009 at 22:47 Comment(1)
There's no need for this. KeyboardEvent already contains properties that indicate whether a key was pressed while Ctrl was being held or not, for example. There is no need for manual detection of the Ctrl key.Luella
W
0
$('my_text_area').focus(function{ set_focus_flag });

//ctrl on key down set flag

//enter on key down = check focus flag, check ctrl flag
Woolsey answered 5/11, 2009 at 22:56 Comment(0)
M
0

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();
    }
});
Mum answered 18/12, 2017 at 19:18 Comment(1)
You could simplify the “ifelse if” to a single if (e.ctrlKey && (e.keyCode == 10 || e.keyCode == 13)).Netti

© 2022 - 2024 — McMap. All rights reserved.