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
}
});
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
}
});
Share
Improve this question
edited Jun 2, 2015 at 13:44
jezrael
864k102 gold badges1.4k silver badges1.3k bronze badges
asked Mar 30, 2014 at 15:38
Mohd ShahidMohd Shahid
1,6063 gold badges35 silver badges71 bronze badges
2
- possible duplicate of How to listen for Ctrl-P key press in JavaScript? – AGupta Commented Mar 30, 2014 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 Commented Mar 30, 2014 at 15:46
2 Answers
Reset to default 8You 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/7S6Hz/3/
<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>