I am using jquery-select2-4 to search an external database and present the user with search results that he can choose from.
I have a working version running on this jsfiddle.
But if, for example, only 1 search result is returned I want to skip the whole selection process, and just add the returned search result to the list of selected options. According to the select2 docs I can add a new option like this:
option = new Option("Sample text", "123", true, true);
select2_element.append(option);
select2_element.trigger('change');
This seems to work to some extent. But there are a few problems.
- I can't clear the search field upon adding the option.
- I can't add anything else that an
id
and atext
. - The added option is displayed to the user as
undefined
.
I realize that this question contains 3 facets, but all 3 facets probably refers back to this 1 question:
How do you programmatically add a new jquery-select2-4 option and reset the search field?
For your reference, this is the context of the code I'm asking about:
var formatRepo, formatRepoSelection, selectRepos;
formatRepoSelection = function(element) {
return element.name + ' ' + element.forks + ' ' + element.id;
};
formatRepo = function(element) {
var markup;
if (!element.loading) {
return markup = element.name + ' ' + element.id;
}
};
selectRepos = function() {
var option, select2_element;
select2_element = $('#select2_element');
select2_element.select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
data: function (params) {
return {
q: params.term,
page: params.page
};
},
processResults: function (data, params) {
if (data.items.length === 1) {
// START: The code I am asking about.
// Add the search result directly as an option.
option = new Option("Sample text", "123", true, true);
select2_element.append(option);
return select2_element.trigger('change');
// END: The code I am asking about.
} else {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
}
},
cache: true
},
escapeMarkup: function(markup) {
return markup;
},
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
};
$(function() {
return selectRepos();
});