Reputation: 7877
The javascript event object offers keyCode() and charCode() methods such that charCode() returns 0 for keys that don't cause a character to be displayed like enter, key up, key down, delete, backspace, etc.
I want to check for exactly these characters inside a jQuery keypress
event callback, but the jQuery event object doesn't give me access to the mentioned methods.
Can I retrieve the js event object from the jQuery one ?
Upvotes: 3
Views: 6155
Reputation: 13720
Key code lists are available all over the internet though here is the heavy lifting done for you without depending on any frameworks...
if (window.addEventListener) {document.addEventListener('keydown',keyPressed,false);}
else {document.attachEvent('onkeydown',keyPressed);}
function keyPressed(evt)
{
var e = evt || event;
var key = e.which || e.keyCode;
if (!powerKeysEnabled) return;
if (showmeallcodes) {alert( key); return;}
switch (key)
{
case 77:// M
alert('m key pressed');
break;
case 76://L
alert('L key pressed');
break;
}
}
Upvotes: 1
Reputation: 4288
$('#yourid').bind('keypress', function(e) {
var keycode= (e.keyCode ? e.keyCode : e.which);
if(keycode == 13){
// Enter pressed... do anything here...
}else if(keycode == 46){// delete
}else if(keycode == 8){ // backspace
}
});
Explorer doesn't fire the keypress event for delete, end, enter, escape, function keys, home, insert, pageUp/Down and tab.
If you need to detect these keys, do yourself a favour and search for their keyCode onkeydown/up, and ignore both onkeypress and charCode.
Upvotes: 4