简体   繁体   中英

If certain keys are pressed with jQuery

I am building a web application and I need to figure this out.

For this project I need to use the keyup function. This on it's own is not that difficult:

if (e.keyCode == 40) { //Up arrow key
    moveListUp();
} else if(e.keyCode == 38){ //Down arrow key
    moveListDown();         
} else{
    $('.searchBox').focus();
}

As you can see, if the arrow keys are pressed, it needs to execute a function. But when any other key is pressed, it executes the focus function on the searchBox.

I don't want every key except the left and right arrow key to trigger the focus function. I only want numeric and alphabetic keys to trigger that function.

How can I achieve this without having to define an if-statement for every single key?

You can just check your key against a regex like that:

$(window).on('keydown', function(e){
    var key_char = String.fromCharCode(e.keyCode),
        regex = /[a-zA-Z0-9]/;

    if (e.keyCode == 40) { //Up arrow key
        moveListUp();
    } else if(e.keyCode == 38){ //Down arrow key
        moveListDown();         
    } else if( regex.test(key_char)){ // matches only alphanumeric keys
      $('.searchBox').focus();
    }
});

If I understand you correctly, you want to check that the key is alphanumeric before calling focus() , in which case you can check that the code is within one of the correct ranges.

else if ((e.keyCode >= 65 && e.keyCode <= 90) || (e.keyCode >= 48 && e.keyCode <= 57) || (e.keyCode >= 97 && e.keyCode <= 122))
{
     $('.searchBox').focus();
}

That is else if ((uppercaseLetter) || (Number) || (lowercaseLetter))

Use return false at last else condition:

if (e.keyCode == 40) { //Up arrow key
    moveListUp();
} else if(e.keyCode == 38){ //Down arrow key
    moveListDown();         
} else if(e.keyCode > 46 || e.keyCode < 91){
    $('.searchBox').focus();
} else{
   return false;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM