0

What I need to do: Detect when a user enters '@' in the textbox

What jQuery 'keyup' or 'keydown' events do: It first detects a keyup/keydown when shift is pressed and another keyup/keydown when '2' is pressed. In order to make '@'.

How to make it identify a '@'?

Sahil
  • 315
  • 5
  • 21

2 Answers2

1

For browser which support DOM3 event.key,

textbox.onkeyup = function(e) {
    if(e.key === '@') alert('@ detected');
};

Demo

Since event.key is not widely supported, you should have a event.keyCode or event.which fallback.

The problem is that those only contain the number of the key which produced the character, not the character itself. And in my keyboard, @ doesn't have its own key, it must be produced with Ctrl+Shift+2 or Alt Gr+2.

Then, for keyboards like mine, you can use

textbox.onkeyup = function(e) {
    if(e.key === '@'
       ||
       e.altKey && e.ctrlKey && (e.keyCode||e.which)===50
    ) 
        alert('@ detected');
};

Demo

Oriol
  • 274,082
  • 63
  • 437
  • 513
0
$("#Txtbox").keyup (function(e) {
    if (e.keyCode == 50)
    {
        if (e.shiftKey === true)
        {
            alert ('@ was pressed' );
        }
        else
        {
            // do nothing
        }

    }
});

Please read this https://developer.mozilla.org/en-US/docs/Web/API/event.keyCode Notes In a keypress event, the Unicode value of the key pressed is stored in either the keyCode or charCode property, never both. If the key pressed generates a character (e.g. 'a'), charCode is set to the code of that character, respecting the letter case. (i.e. charCode takes into account whether the shift key is held down). Otherwise, the code of the pressed key is stored in keyCode.

keyCode is always set in the keydown and keyup events. In these cases, charCode is never set.

To get the code of the key regardless of whether it was stored in keyCode or charCode, query the which property.

Characters entered through an IME do not register through keyCode or charCode.

stackunderflow
  • 3,811
  • 5
  • 31
  • 43