簡體   English   中英

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指定將建議建議創建新標簽的操作。 每次在文本框中進行更改都會執行此操作如此處指定 ),而不是在沒有匹配項時執行。

因此,解決方案是:

  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
            };
        }
    }
});

並且您可以看到它在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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM