2013-10-16 84 views
2

在rails 4.0中,我使用的是select2()插件。在这个领域,我只需要输入唯一的标签,但现在它接受重复的条目。如何避免重复条目?请帮我解决这个问题。如何避免bootstrap的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> 

回答

0

检查以下在选择事件,并在createSearchChoice设置是否新款财产

让我知道如果它解决您的问题

$('#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; 
        } 
       }); 
      } 
     })