2

I am trying to find out the character pressed with ctrl key using jQuery but I am not able to figure out the code.

e.g: If I press ctrl+a then it should alert me that ctrl+a is pressed.

I am using below code

  $(document).keypress(function(e) {
  if(e.ctrlKey){
     var ch = String.fromCharCode(e.keyCode);
     alert("key pressed ctrl+"+ch); //gives blank value in ch here, I need to know the             character pressed
     alert("key pressed ctrl+"+e.keyCode); //this works but gives me ASCII value of the key 
   }
});
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Mohd Shahid
  • 1,538
  • 2
  • 33
  • 66
  • possible duplicate of [How to listen for Ctrl-P key press in JavaScript?](http://stackoverflow.com/questions/12517819/how-to-listen-for-ctrl-p-key-press-in-javascript) – Aman Gupta Mar 30 '14 at 15:42
  • I checked above suggested url but that is different from my above question, I need to know the character code of the pressed key while the suggested url is capturing a single key only. – Mohd Shahid Mar 30 '14 at 15:46

2 Answers2

7

You have to use keydown event to capture the key code reliably:

$(document).keydown(function(event) {
    console.log(event);
    if (!event.ctrlKey){ return true; }
    $("#result").text(String.fromCharCode(event.which));
    event.preventDefault();
});

http://jsfiddle.net/7S6Hz/3/

Max Al Farakh
  • 4,386
  • 4
  • 29
  • 56
0
<html>
<head>
<title>ctrlKey example</title>

<script type="text/javascript">

function showChar(e){
  alert(
    "Key Pressed: " + String.fromCharCode(e.charCode) + "\n"
    + "charCode: " + e.charCode + "\n"
    + "CTRL key pressed: " + e.ctrlKey + "\n"
  );
}

</script>
</head>

<body onkeypress="showChar(event);">
<p>Press any character key, with or without holding down the CTRL key.<br />
You can also use the SHIFT key together with the CTRL key.</p>
</body>
</html>
Anri
  • 1,706
  • 2
  • 17
  • 36