Reputation: 931
I am using a select2 jQuery plugin with ajax autocomplete from a remote server. But the user input gets appended to the dropdown list. Can someone help me with how to not display the user input in the select2 autocomplete dropdown?
here is my js code
$('#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'}]}
}
},
});
Upvotes: 1
Views: 593
Reputation: 931
Finally, I figured it out. Here is how I fix it:
$('#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'}]}
}
},
});
Here, I have overwritten the templateResult and put a check if the item has no name and email (that will be the user input) just return true don't add it to the dropdown list.
Upvotes: 1