Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture cmd + enter event in jquery

I need to determine when a user presses cmd+enter after typing a text into a textarea. I'm using jquery.

Here's what I tried:

<textarea id="checkMetaKey"></textarea>
<div id="display"></div>

$( "#checkMetaKey" ).keyup(function( event ) {
  $( "#display" ).text(event.metaKey + " " + event.keyCode);
});

JSFiddle: http://jsfiddle.net/WQG2b/

I would expect that to display "true 13" when cmd+enter is clicked. It's not the case however.

The only way I can get metaKey to be true is when I click CMD only or CMD+ALT or CMD+CTRL.

How do I capture a CMD+ENTER event?

Similar functionality seems to be working when I try it on Facebook, I'm able to submit message text using CMD+ENTER.

like image 950
vrepsys Avatar asked Dec 26 '13 11:12

vrepsys


People also ask

How do you find Enter key is pressed in jQuery?

The “enter” key is represent by code “13”, check this ASCII charts. To check if an “enter” key is pressed inside a textbox, just bind the keypress() to the textbox. $('#textbox').

How do you trigger click event on pressing Enter key?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.

How do you check Enter key is pressed in JavaScript?

And the following JavaScript code to detect whether the Enter key is pressed: const input = document. querySelector("input"); input. addEventListener("keyup", (event) => { if (event.


1 Answers

Use keydown. Also you should compare event.keyCode == 13

$("#checkMetaKey").keydown(function (event) {
    $("#display").text((event.metaKey || event.ctrlKey) && event.keyCode == 13);
});

$("#checkMetaKey").keydown(function (event) {
    $("#display").text((event.metaKey || event.ctrlKey) &&  event.keyCode == 13);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<textarea id="checkMetaKey"></textarea>
<div id="display"></div>
like image 80
Satpal Avatar answered Oct 23 '22 08:10

Satpal