Select2 Dropdown autoselect if only 1 option available

£可爱£侵袭症+ 提交于 2019-11-29 11:55:01

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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!