Select2 open dropdown on focus

前端 未结 16 2202
陌清茗
陌清茗 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:42

    Something easy that would work on all select2 instances on the page.

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

    UPDATE: The above code doesn't seem to work properly on IE11/Select2 4.0.3

    PS: also added filter to select only single select fields. Select with multiple attribute doesn't need it and would probably break if applied.

    var select2_open;
    // open select2 dropdown on focus
    $(document).on('focus', '.select2-selection--single', function(e) {
        select2_open = $(this).parent().parent().siblings('select');
        select2_open.select2('open');
    });
    
    // fix for ie11
    if (/rv:11.0/i.test(navigator.userAgent)) {
        $(document).on('blur', '.select2-search__field', function (e) {
            select2_open.select2('close');
        });
    }
    

提交回复
热议问题