Select2:修剪输入空格

时间:2017-07-26 10:50:07

标签: jquery-select2

我正在使用Select2

<script type="text/javascript">
$(document).ready(function() {
  $(".select2").select2();
});
</script>

<select class="select2">
  <option>Anna</option>
  <option>Bob Hunter</option>
</select>

我希望在搜索Anna时找到Anna,即使名称之前或之后有空格。如果可能的话,我甚至希望将多个空格总是减少到一个,这样Bob Hunter就会找到Bob Hunter。这样的事情可能吗?我在options docs中找不到类似的东西。

1 个答案:

答案 0 :(得分:1)

您可以使用以下代码在开头修剪空格&amp;端

    jQuery(element).select2({
        matcher: function (params, data) {
        // If there are no search terms, return all of the data
        if (jQuery.trim(params.term) === '') {
            return data;
        }
        var myTerm = jQuery.trim(params.term);
        // `params.term` should be the term that is used for searching
        // `data.text` is the text that is displayed for the data object
        if (data.text.toLowerCase().indexOf(myTerm.toLowerCase()) > -1) {
            // You can return modified objects from here
            // This includes matching the `children` how you want in nested data sets
            return data;
        }

        // Return `null` if the term should not be displayed
        return null;
        }
    });