hemiz
hemiz

Reputation: 91

Using keydown for all Web browsers

Can someone help me, how can i define the keyCode,which,charcode into variable. below is my code. but seems not working in Firefox. i already try at Google chrome and i.e. and its work fine.

    $(function() {
      $('#txtInput').keydown(function(event) {

      var Key = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
            //number
        if (Key >= 48 && Key <= 57)
            return true;
        //numpad
        else if (Key >= 96 && Key <= 105)
            return true;
        //backspace,tab
        else if (Key >= 8 && Key <= 9)
            return true;
        else return false;
    });
});

Upvotes: 2

Views: 91

Answers (1)

thecodeparadox
thecodeparadox

Reputation: 87073

I think event.which is enough to check the keyCode and work fine for all browsers.

According to jQuery doc:

The event.which property normalizes event.keyCode and event.charCode. It is recommended to watch event.which for keyboard key input.

More

event.which also normalizes button presses (mousedown and mouseupevents), reporting 1 for left button, 2 for middle, and 3 for right. Use event.which instead of event.button.

CODE

$('#txtInput').keydown(function(event) {

    var Key = event.which;
    //number
    if (Key >= 48 && Key <= 57) {
        alert('number');
        return true;
    }
    //numpad
    else if (Key >= 96 && Key <= 105) {
        alert('numpad');
        return true;
    }
    //backspace,tab
    else if (Key >= 8 && Key <= 9) {
        alert('backspace, tab');
        return true;
    }
    else return false;
});

Working sample

Read more about event.which

Upvotes: 4

Related Questions