Select2 open dropdown on focus

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

    For Version 3.5.4 (Aug 30, 2015 and earlier)

    The current answer is only applicable to versions 3.5.4 and before, where select2 fired blur and focus events (select2-focus & select2-blur). It attaches a one-time use handler using $.one to catch the initial focus, and then reattaches it during blur for subsequent uses.

    $('.select2').select2({})
      .one('select2-focus', OpenSelect2)
      .on("select2-blur", function (e) {
        $(this).one('select2-focus', OpenSelect2)
      })
    
    function OpenSelect2() {
      var $select2 = $(this).data('select2');
      setTimeout(function() {
        if (!$select2.opened()) { $select2.open(); }
      }, 0);  
    }
    

    I tried both of @irvin-dominin-aka-edward's answers, but also ran into both problems (having to click the dropdown twice, and that Firefox throws 'event is not defined').

    I did find a solution that seems to solve the two problems and haven't run into other issue yet. This is based on @irvin-dominin-aka-edward's answers by modifying the select2Focus function so that instead of executing the rest of the code right away, wrap it in setTimeout.

    Demo in jsFiddle & Stack Snippets

    $('.select2').select2({})
      .one('select2-focus', OpenSelect2)
      .on("select2-blur", function (e) {
        $(this).one('select2-focus', OpenSelect2)
      })
    
    function OpenSelect2() {
      var $select2 = $(this).data('select2');
      setTimeout(function() {
        if (!$select2.opened()) { $select2.open(); }
      }, 0);  
    }
    body {
      margin: 2em;
    }
    
    .form-control {
      width: 200px;  
      margin-bottom: 1em;
      padding: 5px;
      display: flex;
      flex-direction: column;
    }
    
    select {
      border: 1px solid #aaa;
      border-radius: 4px;
      height: 28px;
    }
    
    
    
    
      
      

提交回复
热议问题