Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve keyCode and charCode from a jQuery event object?

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 ?

like image 283
Daud Avatar asked Jun 30 '26 22:06

Daud


2 Answers

$('#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.

like image 118
erimerturk Avatar answered Jul 06 '26 06:07

erimerturk


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;
 }
}
like image 43
John Avatar answered Jul 06 '26 04:07

John



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!