Domanda

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.

È stato utile?

Soluzione

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

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top