javascript - 如何从 select2 下拉列表中删除用户输入
问题描述
我正在使用来自远程服务器的带有 ajax 自动完成功能的 select2 jQuery 插件。但是用户输入会附加到下拉列表中。有人可以帮助我如何不在 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并检查该项目是否没有名称和电子邮件(这将是用户输入)只是返回 true 不要将其添加到下拉列表中。
推荐阅读
- javascript - 从外部 SVG 调用全局定义的 JavaScript 函数
- c# - 在单个 IPublicClientApplication.AcquireTokenSilent 调用中混合图形和 customAPI 范围
- discord - ReferenceError:消息未定义
- php - 当 REDIS 想要过期时如何做某事
- c# - 当我们点击英雄卡的按钮时,我们可以在聊天窗口中启用自动向下滚动吗?
- node.js - toPkcs12Asn1 所需的参数
- ios - 如何在 swift 4 中将此字符串转换为字典
- appium - 如何在我的 appium 本机应用程序测试中添加类似 isClickable() 的内容
- angular - 需要在 Ag-Grid 中修复 SrNo
- java - 将对象拖放到舞台外的新窗口