How to programmatically inject search queries into Select2 v4?

前端 未结 5 1090
刺人心
刺人心 2020-12-14 16:17

I\'ve built a web-app using a Select2 search box, which connects to our backend via AJAX. The search box passes the query (say \"APPLES\") to the backend, which then updates

5条回答
  •  误落风尘
    2020-12-14 16:42

    Select2 used to provide a select2('search', 'term') helper method that would have assisted with this, but it was not brought over to Select2 4.0.0.

    There are a couple of ways that this could be done, but in general they all follow the same pattern of steps

    1. Open the Select2 dropdown
    2. Enter the search text into the search box
    3. Trigger the keyboard events necessary for Select2 to start searching (usually input)

    So, right now, in Select2 4.0.0 the code to do that would look like

    $('select').select2();
    
    function select2_search ($el, term) {
      $el.select2('open');
      
      // Get the search box within the dropdown or the selection
      // Dropdown = single, Selection = multiple
      var $search = $el.data('select2').dropdown.$search || $el.data('select2').selection.$search;
      // This is undocumented and may change in the future
      
      $search.val(term);
      $search.trigger('keyup');
    }
    
    $('button').on('click', function () {
      var $select = $($(this).data('target'));
      select2_search($select, 'Arizona');
    });
    
    
    
    
    
    
    
    
    

    While this example does not use AJAX, it will trigger an AJAX request if Select2 is configured for it.

提交回复
热议问题