Reputation: 8424
I am trying capture character codes using keyUp in jQuery. I'm trying to capture both when the = sign (not on the numeric keyboard) and the + sign (also not on the numeric keyboard) are pressed. The thing is, the character key for them is both. If you press it normally, you get =. If you shift+press it, then you get +. My code goes like this:
(document).keyup(function(evt) {
keyPressed = evt.keyCode ? evt.keyCode : evt.charCode;
switch (keyPressed) {
case 187: // perfectly captures the equal key pressed
case ???: // what should I put here
// ........
So how do I capture (possibly in this case statement) when they key PLUS shift is being pressed? Is there some elegant way to do it?
Upvotes: 1
Views: 50
Reputation: 339
There's a handler for the keyup
event called shiftKey
:
$(document).keyup(function(evt) {
keyPressed = evt.keyCode ? evt.keyCode : evt.which;
switch (keyPressed) {
case 187:
if (evt.shiftKey)
alert("+");
else
alert("=");
break;
}
});
See Fiddle
keypress
instead of keyup
(The keycode
's are different). Take a look
$(document).keypress(function(evt) {
keyPressed = evt.keyCode ? evt.keyCode : evt.which;
switch (keyPressed) {
case 61:
alert("=");
break;
case 43:
alert("+")
break;
}
});
See Fiddle
Upvotes: 0
Reputation: 74420
Your best bet is to use keypress
event:
$(document).keypress(function (evt) {
var keyPressed = String.fromCharCode(evt.which);
console.log(keyPressed)
});
event.which is normalized
Upvotes: 0
Reputation: 136154
evt
has another property of interest to you - shiftKey
, which is a boolean indicating that the shift key was pressed. Therefore you can do this:
$(document).keyup(function(evt) {
keyPressed = evt.keyCode ? evt.keyCode : evt.charCode;
if(keyPressed == 187){
if(evt.shiftKey){
// is + as shift was also pressed
}
else{
// is =
}
}
});
Upvotes: 2
Reputation: 74738
Instead you can use the same keycode
and check in the case that shiftkey
is pressed:
switch (keyPressed) {
case 187:
if(evt.shiftKey){
console.log('+');
}else{
console.log('=');
}
break;
}
Upvotes: 0