I cannot get preventDefault()
to work.
Here are some different code variations I have tried:
First:
$(document).keyup(function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 192) {
alert('192');
return false;
}
});
Second:
$(document).keyup(function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 192) {
alert('192');
evt.preventDefault();
}
});
Third:
$(document).keyup(function (evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if (charCode == 192) {
alert('192');
evt.preventDefault();
return false;
}
});
Only alert works.
Everything works on Opera,but not on Chrome and IE
Also tried keydown
and keypress
.
On keypress
script doesn't work.
$('#thetext').keydown(function(evt){});
neither works this.
Here is whole code: http://bbullett.tk/test/kakey.html
Key 192 = `
I'm trying to insert some text or symbol instead of `
The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur. For example, this can be useful when: Clicking on a "Submit" button, prevent it from submitting a form. Clicking on a link, prevent the link from following the URL.
preventDefault() The preventDefault() method of the Event interface tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be.
To prevent a default action – use either event. preventDefault() or return false .
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With