I cannot get preventDefault()
to work.
Here are some different code variations I have tried:
First:
$(document).keyup(function (evt)
Listening to keyup
event is too late for calling preventDefault
, try listening to keypress
or keydown
instead.
$('input[type=text], textarea').on('keydown', function(event){
if (event.which == 192) {
console.log('192');
event.preventDefault();
}
});
Note that jQuery normalizes which
property and it's cross-browser.
http://jsfiddle.net/763ys/
see working example here http://jsfiddle.net/WGSvm/
In all three examples you have used
$(document).keyup(function (evt) { });
I would say use particular div id instead of $(document).keyup(function (evt) { });
like $("#DivIdName").keyup(function (evt) { });
and also use onkeypress
strictly, because if you use onkeyup
it has already executed its default task of printing or whatever it is.
There is no default behaviour for .keyup()
; it fires after the key press which triggers the default behaviour. Use .keydown() or
.keypress()` instead.
source: http://api.jquery.com/category/events/keyboard-events/
You are using JQuery, which normalises the differences between browsers, so you only need to to check the evt.which property. See the JQuery documentation: http://api.jquery.com/keyup/
As others have said - keyup is too late to stop the processing of the key. Use keydown or keypress instead. http://api.jquery.com/category/events/keyboard-events/