【问题标题】:How to avoid duplicate entries in bootstrap's select2() plugin如何避免引导程序的 select2() 插件中的重复条目
【发布时间】:2013-10-16 08:08:48
【问题描述】:

在 rails 4.0 中,我使用的是 select2() 插件。在这个字段中,我只需要输入唯一的标签,但现在它正在接受重复的条目。如何避免重复条目?请帮我解决这个问题。

在视图中,

<script type="text/javascript">
 $('#DIV_USERNAME').select2({
  placeholder: "Search for a names",
  multiple: true,
  ajax: { 
    url: "autocomplete/names",
    dataType: 'json',
    data: function (term) {
    return { q: term };
   },
   results: function (data) {
     return {results: data};
   }
  },
  createSearchChoice: function (term) {
    return { id: term, text: term };
  }
 });
</script>

【问题讨论】:

    标签: jquery ruby-on-rails twitter-bootstrap jquery-select2


    【解决方案1】:

    检查以下 On Selecting 事件,并在 createSearchChoice

    中设置 isNew 属性

    如果它解决了您的问题,请告诉我

    $('#some_id').select2({
                tags: true,
                tokenSeparators: [","],
                createSearchChoice: function (term, data) {
                    if (term.trim().length > 0) {
                        if ($(data).filter(function () {
                          return this.text.toLowerCase().localeCompare(term.toLowerCase()) === 0;
                        }).length === 0) {
                            return {
                                id: term,
                                text: term,
                                isNew: true // this is necessary to check if the item is newly added or not
                            };
                        }
                    }
                },
                multiple: true,
                minimumInputLength: 1,
                allowClear: true,
                data: [
            {id: 1, text: 'some text'},
            {id: 2, text: 'some other text'},
            {id: 3, text: 'some more text'}
        ],
            }).on("select2-selecting", function (e) {
                var tagId = '';
                if (e.choice.isNew) {
                    self.AddTagToDatabase(e.choice.text);
                } else {
                    var isValidTag = true;
                    $(config.element[0] + ' ul li').find('div').each(function (index, item) {
                        if ($(item).html().toLowerCase().trim() == e.choice.text.toLowerCase().trim()) {
                            isValidTag = false;
                            e.choice.text = '';
                            return;
                        }
                    });
                }
            })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2014-06-17
      • 2017-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多