0
我使用Select2與ajax和自動完成。 我有一個問題,當我輸入一些不存在的東西。 在第一個例子中,我搜索「fr」查看結果,並自動創建標籤!如果我嘗試輸入更多的字符,我不能,因爲我有一個標籤的限制...我點擊「清除」按鈕,我必須寫得很快,標籤創建但自動完成逗留...Select2 4.0.3 - 如果沒有結果創建新標記
$(document).ready(function() {
// example of data: https://api.myjson.com/bins/m0x8
$("#marques").select2({
\t ajax: {
\t \t url: "/ajax/acmarques",
\t \t dataType: 'json',
\t \t delay: 250, // or 600, same result
\t \t processResults: function (data) {
\t \t \t return {
\t \t \t \t results: data
\t \t \t };
\t \t },
\t },
\t escapeMarkup: function(m) {
\t \t return m;
\t },
\t createTag: function(item) {
return {
id: item.term,
text: item.term,
};
},
\t maximumSelectionLength: 1, // only 1 tag is possible
\t tags: true,
\t //language: "fr",
\t allowClear: true,
\t placeholder: "Indiquez la marque de la croquette."
});
});
#marques {
width: 300px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
</head>
<body>
<div>
<label for="marques">select2 with ajax/autocomplete</label><select id="marques"></select>
</div>
</body>
</html>
第二個截屏是更好的,但我不能 「驗證」 誰不存在新的標籤。 我認爲最好的方法是用createTag中的這個小代碼捕捉ENTER/TAB鍵。
Test with createtag return null
createTag: function(item) {
// Don't offset to create a tag if there is no @ symbol
if (item.term.indexOf('@') === -1) {
// Return null to disable tag creation
return null;
}
return {
id: item.term,
text: item.term,
};
},
你有一個想法,以解決我的問題?我嘗試了很多在github和stackoverflow上找到的東西,但它經常用於舊版本的select2。
非常感謝