Lamps1829
Lamps1829

Reputation: 2451

How to disable arrow keys for dropdown/selector element?

What is a good jquery/javascript approach to prevent a user from using the up and down arrow keys to select options in a dropdown box (i.e. to force the user to only use the mouse to select menu options)? Thanks!

Upvotes: 3

Views: 9450

Answers (2)

koolness
koolness

Reputation: 166

FOR LATEST FIREFOX & CHROME ( IE anyone? ;-)

I've adapted some code to mimic disabling Up and Down arrow keys as required. I had to do similar with arrowUp / pageUp and arrowDown / pageDown keys for my app in order to allow custom keyboard navigation (I preserved arrowLeft / arrowRight key functionality for vertical menu navigation). Notice that I applied a setTimeout, this seems to be needed for Firefox (latest) :

$(document).on('keydown', 'select', function (e) {
var optsel = $(this).find('option:selected').val();
if ( (e.which == 38 || e.which === 40) ) {
setTimeout(function(){$('select option[value="' + optsel +'"]').prop("selected", true)}, 0);
}
});

The trick was to save as variable the last value selected of select menu, then recalling it with the setTimeout method as required by Firefox (at least).

Upvotes: 0

Naftali
Naftali

Reputation: 146350

#1. don't do that, it futzes with user experience

But if you are:

$('select').on('keydown', function(e){
    if(e.keyCode === 38 || e.keyCode === 40) { //up or down
        e.preventDefault();
        return false;
    }
});

Upvotes: 11

Related Questions