2013-11-23 140 views
2

如何避免Select2輸入中的重複標籤?Select2 - 避免重複標籤

當我鍵入鍵盤上的標籤名字符串被添加到輸入字段,但是當我從下拉列表中選擇標籤(來自數據庫的結果)時,該id被添加到輸入中(查看截圖中的console.log)。所以我可以從列表中選擇標籤並從鍵盤添加相同的標籤。

此外,我需要text的標籤,而不是id從下拉列表中提交表單。

console.log

Full resolution

HTML:

<input type="hidden" id="categories" name="categories" style="width:100%" value="${categories}"> 

JS:

$("#categories").select2({ 
    tags: true, 
    tokenSeparators: [","], 
    placeholder: "Dodaj", 
    multiple: false, 
    minimumInputLength: 3, 
    maximumInputLength: 50, 
    maximumSelectionSize: 20, 
    ajax: { 
     quietMillis: 150, 
     url: '${request.route_url("select2")}', 
     dataType: 'json', 
     data: function (term, page) { 
      return { 
       q: term, 
       page_limit: 10, 
       page: page, 
      }; 
     }, 
     results: function (data, page) { 
      var more = (page * 10) < data.total; 
      return {results: data.categories, more: more}; 
     } 
    }, 
    initSelection: function (element, callback) { 
     var data = []; 
     $(element.val().split(",")).each(function() { 
      data.push({id: this, text: this}); 
     }); 
     callback(data); 
    }, 
    createSearchChoice: function (term) { 
     return { id: term, text: term }; 
    }, 
}).change(function (e) { 
    if (e.added) { 
     console.log($("#categories").val()) 
     console.log(e) 
    } 
}); 
+0

注意select2的3.3.0和3.3.1有一個與重複值有關的錯誤... – mccannf

+0

謝謝。我正在使用最新的3.4.5。 – kros

+0

我有同樣的問題。我得到重複。我開始選擇,但之後在ajax上稱它忽略了現有的價值並添加重複。 – Yaron

回答

0

有同樣的問題,但我想通過找到解決辦法。 我得到的文本和ID,但在服務器端,我從給定的ID創建新的對象,這是很好的閱讀。

$tagsArray = explode(',', $tagNames); // it contains of my input select2 value (with ids) 

foreach ($tagsArray as $tag) 
{ 
    if (is_numeric($tag)) 
    { 
     $tags->append(TagQuery::create()->filterById($tag)->findOneOrCreate()); 
    } 
    elseif (!empty($tag)) 
    { 
     $tags->append(TagQuery::create()->filterByName($tag)->findOneOrCreate()); 
    } 
} 

希望它有幫助。