[英]How to remove user input from select2 dropdown list
我正在使用 select2 jQuery 插件和 ajax 從遠程服務器自動完成。 但是用戶輸入會附加到下拉列表中。 有人可以幫助我如何不在 select2 自動完成下拉列表中顯示用戶輸入嗎?
這是我的js代碼
$('#id_available_users').select2({
placeholder: "Select an Existing User",
allowClear: true,
minimumInputLength: 3,
tags: [],
ajax: {
url: '/api/users/',
dataType: 'json',
type: "GET",
data: function (term) {
return {
query: term.term,
};
},
processResults: function (data) {
if (data.length > 0)
{
return {
results: $.map(data, function (item) {
return {
text: item.name + ', ' + item.email + ', ' + item.location.city + ' ' + item.location.state + ' ' + item.location.zip + ' ' + item.location.country,
id: item.id,
}
})
};
}
else return {results: [{ 'loading' : false, 'description' : 'No result', 'name' : 'no_result', 'text' : 'No result'}]}
}
},
});
最后,我想通了。 這是我修復它的方法:
$('#id_available_users').select2({
placeholder: "Select an Existing User",
allowClear: true,
minimumInputLength: 3,
tags: [],
templateResult: function formatState (state) {
if (!state.id) {
return state.text
}
if (!state.text.name && !state.text.email) {
return; // here I am excluding the user input
}
var $state = '<p><b>'+ state.text.name + '</b>, ' + state.text.email + ', ' + state.text.location.city + ' ' + state.text.location.state + ' ' + state.text.location.zip + ' ' + state.text.location.country +'</p>';
return $state;
},
ajax: {
url: '/api/users/',
dataType: 'json',
type: "GET",
data: function (term) {
return {
query: term.term,
};
},
processResults: function (data) {
if (data.length > 0)
{
return {
results: $.map(data, function (item) {
return {
text: item,
id: item.id,
}
})
};
}
else return {results: [{ 'loading' : false, 'description' : 'No result', 'name' : 'no_result', 'text' : 'No result'}]}
}
},
});
在這里,我已經覆蓋了templateResult並檢查了該項目是否沒有名稱,並且 email (這將是用戶輸入)只是返回 true 不要將其添加到下拉列表中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.