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.
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
If the question is now: why does
alert()make a difference?alertis a funny statement (andconfirmandprompt), it suspends execution of your JavaScript, but frees up any other browser processing that was waiting for your JavaScript to execute. It can interfere with debugging quite a lot.The browser won’t respond to your
preventDefault()statement until your JavaScript has finished, puttingalertin there has suspended your JavaScript, so the browser hasn’t received a return status of the event at this point, and unfortunately thealerthas allowed the browser to process other events, namelykeypresswhich sneaks past and hence you see the character you don’t want to be typed appear.You could not use
alert, or, if you need it (?!) you could issue it wrapped in asetTimeout, so that it doesn’t block your JavaScript and the result of thekeydownwill lead to thekeypressbeing suppressed.—
Or, you could have used
keypressin the first place!That still doesn’t prevent characters being entered by alternative methods though, so I wouldn’t entertain this in the first place, personally. :-/