0

I want to detect these two behaviours on an input field:

1)Backspace key

2)"@" and "#" key

By using jQuery's keypress function, I am able to detect the special characters but not backspace. LINK -> How to know if .keyup() is a character key (jQuery)

By using jQuery's keyup/keydown, I am able to detect backspace, but not special characters. LINK -> jQuery: keyPress Backspace won't fire?

How can I detect both the behaviours ?

NOTE: Keypress can detect backspace in firefox only. Chrome doesn't detect this.

Community
  • 1
  • 1
Ateev Chopra
  • 1,026
  • 2
  • 15
  • 32
  • What's wrong with keyup event? Not sure to understand your issue. Could you provide a jsFiddle? – A. Wolff May 02 '14 at 14:19
  • With that, I cannot detect backspace on chrome. (check the link provided) – Ateev Chopra May 02 '14 at 14:22
  • `keypress` isn't fired for backspace, `keyup` is. My question was regarding `keyup`. So what's wrong with using `keyup`??? Test it yourself here: http://jsfiddle.net/8W7uV/ EDIT: ok, i see now what you mean by "special keys" – A. Wolff May 02 '14 at 14:24

1 Answers1

0

You can use following snippet:

var keys = {};

$('input').keydown(function (e) {
    keys[e.which] = true;
});

$('input').keyup(function (e) {        
    getKeys();
    delete keys[e.which];    
});

function getKeys() {    
   if(keys[8]) {
        alert('bakspace pressed');
    }else if(keys[17] && keys[18] && keys[48]) {
        alert('@ pressed');
    }else if(keys[17] && keys[18] && keys[51]) {
        alert('# pressed');
    }    
}

DEMO

original post: https://stackoverflow.com/a/4954480/1414562

Community
  • 1
  • 1
A. Wolff
  • 74,033
  • 9
  • 94
  • 155