2015-06-19 27 views
1

我試圖只允許select2庫中的一個值,不管它是如何寫入的。例如,如果值「Test」在數據列表中,則不應再添加「test」。我搜索了一段時間,也查看了文檔,但我沒有解決這個問題。select2:禁用區分大小寫的匹配

 $("#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/

回答

4

的問題是,你正在運行的matcher方法全部比較時,你應該在createTag方法來運行它們:

  • 通過默認情況下,matcher不區分大小寫,您不需要爲此運行任何特殊代碼。請注意,如果您刪除該函數並鍵入「test」,則建議將包含「測試」(即使在用小寫字母t編寫時,大寫T也是如此)。

  • createTag指定將運行以建議新標籤創建的操作。 它在文本框as specified here)中的每個更改都執行,而不是在不匹配時執行。

因此,解決辦法是:

  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/(類型「測試」,你會看到的建議怎麼不顯示出特定的價值)。

編輯:此解決方案與遠程數據源不兼容,您可能希望存儲最後的值或直接檢查標記是否存在時的ajax結果。

+1

我可能還要注意,默認情況下,只有當'createTag'中返回的'id'與任何​​res中的'id'都不匹配時纔會顯示標籤ULTS。 –

+0

謝謝,這幫了我很多! @凱文布朗:一個很好的提示,我會牢記這一點。 – baris1892

0

對於遠程數據源和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 
 
});

  • 注:上面的代碼是用於選擇二4.0.x的
相關問題