Select2 open dropdown on focus

前端 未结 16 2209
陌清茗
陌清茗 2020-12-05 00:21

I have a form with multiple text inputs and some select2 elements. Using the keyboard to tab between fields works fine - the Select2 element behaves like a form element and

16条回答
  •  渐次进展
    2020-12-05 00:50

    I've had the problem which was two pronged:
    1. In a form with multiple select2 elements, the dropdown won't open on tab, and you need to press space key to open it
    2. Once you have made a selection, the tabindex won't be honored and you have to manually click on the next input field

    While the usual suggestions worked, I came up with my own version, since a library script was doing the conversion of normal select to select2, and hence I had no control over this initialization.

    Here is the code that worked for me.

    Tab to open

    $(document).on("focus", ".select2", function() {
        $(this).siblings("select").select2("open");
    });
    

    Move to next on selection

    var inputs = $("input,select"); // You can use other elements such as textarea, button etc. 
                                    //depending on input field types you have used
    $("select").on("select2:close",function(){
        var pos = $(inputs).index(this) + 1;
        var next = $(inputs).eq(pos);
        setTimeout( function() {
            next.focus();
            if (next.siblings(".select2").length) { //If it's a select
                next.select2("open");
            }
        }, 500); //The delay is required to allow default events to occur
    });
    

    Hope this helps.

提交回复
热议问题