select2:禁用区分大小写的匹配

select2: Disable case-sensitive matches

我试图在 select2 库中只允许一个值,无论它是如何编写的。例如,如果值 "Test" 在数据列表中,则不应再次添加 "test"。找了一段时间,也看了文档,没解决这个问题。

        $("#timezones").select2({
            tags: true,
            createTag: function (tag) {
                return {
                    id: tag.term,
                    text: tag.term + " (new)",
                    isNew: true
                };
            },
            matcher: function (term, data) {
                // `term.term` should be the term that is used for searching
                // `data.text` is the text that is displayed for the data object
                if ($.trim(term.term) === '') {
                    return data;
                }

                var termString = term.term.trim();
                var textString = data.text.trim();
                var termStringUpper;
                var textStringUpper;

                if (termString) termStringUpper = termString.toUpperCase();
                if (textString) textStringUpper = textString.toUpperCase();

                return termStringUpper == textStringUpper;
            }
        });

这是一个 JSFiddle:https://jsfiddle.net/2sz0oj8m/

问题是你在 matcher 方法中 运行 所有比较,而你应该在 createTag 方法中 运行 它们:

  • 默认情况下,matcher 不区分大小写,因此您不需要 运行 任何特殊代码。请注意,如果您删除该函数并键入 "test",建议将包括 "Test"(即使您使用小写字母 t 也使用大写字母 T)。

  • createTag 指定将 运行 建议创建新标签的操作。 每次更改文本框时都会执行 (as specified here),而不是在不匹配时执行。

所以解决方案是:

  1. 删除 matcher 方法。
  2. 将大小写比较添加到 createTag 方法。
  3. 如果未找到不区分大小写的匹配项,则仅 return 新建议。

结果是这样的:

$("#timezones").select2({
    tags: true,
    createTag: function (tag) {

        // Check if the option is already there
        var found = false;
        $("#timezones option").each(function() {
            if ($.trim(tag.term).toUpperCase() === $.trim($(this).text()).toUpperCase()) {
                found = true;
            }
        });

        // Show the suggestion only if a match was not found
        if (!found) {
            return {
                id: tag.term,
                text: tag.term + " (new)",
                isNew: true
            };
        }
    }
});

并且您可以在您的 JSFiddle 的这次更新中看到它 运行:https://jsfiddle.net/2sz0oj8m/1/(键入 "test",您将看到该建议如何不针对该特定内容显示值)。

编辑:此解决方案与远程数据源不兼容,如果标签存在,您可能希望存储最后的值或直接签入 ajax 结果。

对于远程数据源和tags:true,我做了如下代码:

$('selector').select2({
    tags: true,
    createTag: function ($params) {
        var $term = $.trim($params.term);
        if ($term === '') {
          return null;
        }

        return {
          id: $term,
          text: $term,
          newTag: true // add additional parameters
        }
    },
    insertTag: function(data, tag) {
        var $found = false;
        $.each(data, function(index, value) {
            if($.trim(tag.text).toUpperCase() == $.trim(value.text).toUpperCase()) {
                $found = true;
            }
        });

        if(!$found) data.unshift(tag);
    },
    // .. other select2 options include remote options 
});

  • 注意:上面的代码是针对Select2 4的。0.x