HTML / Javascript - stop left /right arrow from changing dropdown menu choice

前端 未结 4 661
醉梦人生
醉梦人生 2021-01-24 21:31

I am creating a web form with a grid of inputs for creating objects in Django.

It seems that when the focus is on a drop down menu, the up and left arrows select the pr

4条回答
  •  独厮守ぢ
    2021-01-24 22:26

    Changing default behavior of controls is sometimes frustrating for users. But other times the user expect it works like excel like in your case :)

    You can do something like this:

    var selects = document.getElementsByTagName('select');
    for (var i = 0; i < selects.length; i++){
        selects[i].addEventListener('keydown',function(e){    
            var key = e.which || e.keyCode;
            if(key == 37){
                var previousSibling = this.previousSibling;
                while(previousSibling && previousSibling.nodeType != 1) {
                    previousSibling = previousSibling.previousSibling
                }
                previousSibling.focus();
                e.preventDefault();
            }else if(key === 39){
                var nextSibling = this.nextSibling;
                while(nextSibling && nextSibling.nodeType != 1) {
                    nextSibling = nextSibling.nextSibling
                }
                nextSibling.focus();
                e.preventDefault();
            }
        })
    }
    

    Key 37 = and key 39 is .
    e.preventDefault(); prevents the default behaviour of the key you pressed.

    Fiddle

提交回复
热议问题