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

bar*_*892 3 javascript jquery-select2

我试图在 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;
            }
        });
Run Code Online (Sandbox Code Playgroud)

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

Alv*_*oro 6

问题是,当您应该在matcher方法中运行所有比较时,您却在方法中运行它们createTag

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

  • createTag指定将运行以建议创建新标签的操作。它在文本框中的每次更改(如此处指定)时执行,而不是在不匹配时执行。

所以解决方案是:

  1. 删除该matcher方法。
  2. 将案例比较添加到createTag方法中。
  3. 仅当未找到不区分大小写的匹配项时才返回新建议。

结果会是这样的:

$("#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
            };
        }
    }
});
Run Code Online (Sandbox Code Playgroud)

您可以看到它在 JSFiddle 的此更新上运行:https://jsfiddle.net/2sz0oj8m/1/(输入“test”,您将看到建议如何不会针对该特定值显示)。

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