2

在 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>
4

1 回答 1

0

检查以下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;
                    }
                });
            }
        })
于 2015-03-02T10:57:32.870 回答