Search code examples
jqueryselectdropdownjquery-select2

How to open select2 dropdown on focus when tab pressed


I want auto open select box when it is focused with tab. I use select2 plugin.

here is html code example:

<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>

and other dropdown is this:

<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>

Solution

  • You have to play with event focus , but to avoid infinite focus, you have to trap event closing too

    $(".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>