Prevent keypress whilst shift key is held

Posted by deifwud on Stack Overflow See other posts from Stack Overflow or by deifwud
Published on 2012-06-29T14:25:10Z Indexed on 2012/06/29 15:16 UTC
Read the original article Hit count: 138

Filed under:
|

I'm trying to prevent certain keys from being entered into an input box, but only if that particular key is pressed whilst the shift key is held:

$('selector').keydown(function(e) {
  console.log(e.shiftKey);
  if (e.shiftKey && e.which == 51) {
    e.preventDefault();
    alert('Disallowed');
  }
});

The alert fires but the character still appears in the text box. If I remove e.shiftKey from the if statement and press the key (without shift held), the alert fires and the character does not appear in the text box.

I've tried searching around for an explanation as to why this happens but to no avail, any help would be greatly appreciated!

edit

Removing the alert seems to fix the problem (which seems bizarre), I'd really love to know why it behaves in this way though, it doesn't seem to make any sense.

Thanks

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery