按下选项卡时如何在焦点上打开 select2 下拉菜单

How to open select2 dropdown on focus when tab pressed

我希望在使用选项卡聚焦时自动打开 select 框。我使用 select2 插件。

这里是 html 代码示例:

<div class="col-md-4">
    <div class="form-group">
        <label for="type" class="text-muted">Transaction type</label>
        <span class="ml-1 text-danger">*</span>
       <select name="type" id="type" class="form-control select=search transaction_type" required data-fouc>
            <option value="credit" selected>Credit</option>
            <option value="debit">Debit</option>
        </select>
        @error('type')
        <span class="invalid-feedback" role="alert">
            <strong>{{ $message }}</strong>
        </span>
        @enderror
    </div>
</div>

其他下拉列表是这样的:

<div class="col-md-4">
        <div class="form-group">
            <label for="bank_id" class="text-muted">Related bank</label>
            <span class="ml-1 text-danger">*</span>
            <select name="bank_id" data-select2-id="bank_id" id="bank_id" class="form-control select select2-hidden-accessible bank">
                @foreach($banks as $bank)
                    <option value="{{$bank->id}}">{{$bank->name}}</option>
                @endforeach
            </select>
            @error('bank_id')
            <span class="invalid-feedback" role="alert">
                <strong>{{ $message }}</strong>
            </span>
            @enderror
        </div>
    </div>

你必须玩event focus,但为了避免无限聚焦,你也必须陷害event closing

$(".form-control.select-search").select2();

$(document).on('focus', '.select2-selection.select2-selection--single', function (e) {
  $(this).closest(".select2-container").siblings('select:enabled').select2('open');
})

$(".form-control.select-search").on('select2:closing', function (e) {
  $(e.target).data("select2").$selection.one('focus focusin', function (e) {
    e.stopPropagation();
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/js/select2.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.7/css/select2.css" rel="stylesheet"/>
<div class="form-group">
    <select class="form-control select-search" data-fouc>
        <option value="cheese">Cheese</option>
        <option value="tomatoes">Tomatoes</option>
        <option value="mozarella">Mozzarella</option>
        <option value="mushrooms">Mushrooms</option>
    </select>
</div>