Select2 Dropdown autoselect if only 1 option available

后端 未结 1 435
别那么骄傲
别那么骄傲 2020-12-19 22:01

I have a select2 dropdown box using remote datasource.

What I would like to do is if/when there is only one option returned by the search, auto select it. ie, the us

相关标签:
1条回答
  • 2020-12-19 22:50

    This is a custom matcher, that wraps around the default matcher and counts how many matches there are. If there is only one match, then it will select that match, change it, and close the dropdown box.

    (Not tested with remote data.)

    $(function() {
      
      var matchCount = 0; // Track how many matches there are
      var matched; // Track the ID of the last match
      
      $('select').select2({
        placeholder: 'Product Search',
        allowClear: true,
        matcher: function(params, data) {
          // Wrap the default matcher that we have just overridden.
          var match = $.fn.select2.defaults.defaults.matcher(params, data);
                
          // If this is the first option that we are testing against,
          // reset the matchCount to zero.
          var first = $(data.element).closest('select').find('option').first().val();
          if (first == data.id) matchCount = 0;
          
          // If there was a match against this option, record it
          if (match) {
            matchCount = matchCount + 1;
            matched = data.id;
          }
          
          // If this is the last option that we are testing against,
          // now is a good time to check how many matches we had.
          var last = $(data.element).closest('select').find('option').last().val();
          if (last == data.id && matchCount == 1) {
            
            // There was only one match, change the value to the
            // matched option and close the dropdown box.
            $(data.element).closest('select')
              .val(matched).trigger('change')
              .select2('close');
            return null;
          }
          
          // Return the default match as normal. Null if no match.
          return match;
        }
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.full.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
    
    <select style="width: 20em">
      <option value=""></option>
      <option value="100">Product One</option>
      <option value="200">Product Two</option>
      <option value="300">Product Three</option>
      <option value="400">Product Four</option>
      <option value="500">Product Five</option>
    </select>

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