daremkd
daremkd

Reputation: 8424

Distinguish between = and + on keyUp

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

Answers (4)

gioNicol
gioNicol

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


Or, depending on what you want to do, you could also try using 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


Also check - Difference between keyup and keypress

Upvotes: 0

A. Wolff
A. Wolff

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

Jamiec
Jamiec

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

Jai
Jai

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

Related Questions