2015-06-19 101 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的
相关问题