Select2 - Searching wildcard matches

后端 未结 1 876
借酒劲吻你
借酒劲吻你 2021-01-23 04:12

I am using Select2 to style my select box and add functionality and I am wondering how I can make the search rules more lenient. Currently if I have \"New Mexico\" in the dropdo

相关标签:
1条回答
  • 2021-01-23 04:46

    Alright, apparently you can set custom matchers to accomplish this. I found this one and it seems to be working as desired:

    $(function () { 
        $('.states').select2({
            matcher: function (params, data) {
                if ($.trim(params.term) === '') {
                    return data;
                }
    
                keywords=(params.term).split(" ");
    
                for (var i = 0; i < keywords.length; i++) {
                    if (((data.text).toUpperCase()).indexOf((keywords[i]).toUpperCase()) == -1) 
                    return null;
                }
                return data;
            }
        });
    });
    <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.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
    <select class="states" style="width: 50%">
      <option value="NH">New Hampshire</option>
      <option value="NJ">New Jersey</option>
      <option value="NM">New Mexico</option>
      <option value="TB">Tshirt, Black</option>
    </select>

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