2013-10-16 121 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; 
        } 
       }); 
      } 
     })