Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

preventDefault() on keyup event not working

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 `

like image 377
Solo Omsarashvili Avatar asked Dec 27 '12 12:12

Solo Omsarashvili


People also ask

Why is the event preventDefault() command used?

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.

What does preventDefault() do in javascript?

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.

How to stop Default action in javascript?

To prevent a default action – use either event. preventDefault() or return false .


1 Answers

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/

like image 116
undefined Avatar answered Sep 18 '22 09:09

undefined