Prevent select2 from autmatically focussing its search-input when dropdown is opened

后端 未结 10 446
野性不改
野性不改 2021-01-11 16:02

I\'m looking for a way to prevent select2\'s search-input being automatically focussed when the select2-dropdown is opened. I know this is select2\'s intended default behavi

相关标签:
10条回答
  • 2021-01-11 16:43

    If you want to disable the searchbox and also the auto focus as a text input, e.g. preventing ios browsers to scroll-in the keyboard, use this code:

    $('select').select2({});
    // will remove the searchbox and focus initially
    $(".select2-search, .select2-focusser").remove();
    // will remove the searchbox and focus on selection/close
    $('select').on('select2:closing', function (e) {
      $(".select2-search, .select2-focusser").remove();
    });
    
    0 讨论(0)
  • 2021-01-11 16:43

    None of the solutions posted here worked for me so I did this work around:

    This will make the search input readonly when opened (prevents keyboard on mobile), then when you click the input it removes readonly and opens keyboard.

    $('#myselectbox').select2({placeholder: "Select Something"}).on('select2:open', function(e){
                $('.select2-search input').attr('readonly',true);
            });
    
    $('body').on('click', '.select2-search input', function(){
                $(this).attr('readonly',false);
            });
    
    0 讨论(0)
  • 2021-01-11 16:45

    Ok, I am not sure if changing the focus is possible unless you change the select2 script itself (I could be wrong about this though). As a workaround what you could do is hide the search box by setting minimumResultsForSearch property to a negative value.

    <select id="test">
      <option>1</option>
      <option>2</option>    
    </select>
    

    And then:

    $(document).ready(function() {
       $('#test').select2({
          minimumResultsForSearch: -1
       }); 
    });
    

    Fiddle

    0 讨论(0)
  • 2021-01-11 16:48

    Sometimes select2 "steals" focus from other elements. After messing around for quite a bit, I just used this solution below.

    At the very end of the event handler for the YourSelect2.on('change', function(){

    setTimeout(firstInputFocus, 300);
    

    }

    function firstInputFocus() {

        $("YourSelect2").focus();
    

    }

    By setting this slight delay it works. I am able to change focus away from the dropdown. Following the "change" event for select2, it does something internal to the select2 code which prevents you from IMMEDIATELY changing focus. Inserting this slight delay did the trick for me at any rate.

    0 讨论(0)
提交回复
热议问题