Search code examples
jquerycharkeypresskeydown

Read character from keypress event


i'm trying to make an if statement with jquery to check if an 'abc' char was pressed. I'm hoping to do this with regular expression instead of checking keyboard code/ascii char for each key like this:

$('#main-field').on('keypress, keydown', function(event) {
    if ((event.which != 37 && (event.which != 39)...) {
        code here
    }
}

I know that event.which gives you the keyboard code for each character but how do I reach the char itself that is pressed to check if it is an 'abc' character with reg exp? thanks


Solution

  • You can get the character (a-z) using String.fromCharCode( 65 ). It is a static method that will convert a unicode number to its corresponding character on your keyboard layout.

    var chars = '';
    $('#main-field').on('keypress, keydown', function(event) {
        var character = String.fromCharCode(event.keyCode).toLowerCase();
        chars += character;
        if (chars == 'abc') {
            alert('abc');
        }
    });
    

    So to check if the User typed 'abc' in that order, you can append character to a chars String and compare that to 'abc'

    Here is a fiddle. Note that the Enter key for example will return an empty string, so you might want to think about a fallback for that.