JavaScript: Detect Alt/Option Key on Select Element

3.6k Views Asked by At

I am running this on a Macintosh, hence the option key.

I have a simple menu in HTML as follows:

<select name="select-item">
    <option value="">Test</option>
    <option value="1">One</option>
</select>

It is inside a form element which, in JavaScript has the creatively named form variable.

How can I tell whether the option/alt key is down when a menu item is selected?

I have tried the following code:

form['select-item'].onchange=function(e) {
    alert(e.altKey);
}

but I get undefined as the result, regardless of whether the option key is down or not. The same applies if I try the shift key instead.

No jQuery, please.

1

There are 1 best solutions below

2
On

Try using the keydown event on window and storing the values

var keys = [];
window.onkeyup = function(e) {keys[e.keyCode]=false;}
window.onkeydown = function(e) {keys[e.keyCode]=true;}


form['select-item'].onchange=function(e) {
    alert(keys[18]);  // 18 is the keyCode for alt
}

You can find all keycodes on https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Here is a jsfiddle demo