I\'ve built a web-app using a Select2 search box, which connects to our backend via AJAX. The search box passes the query (say \"APPLES\") to the backend, which then updates
The answers on this page got me almost there. And because others seem to have the same issues, I am sharing how I solved it.
Some of the comments on Kevin Browns answer asked how to simulate the ENTER after the text has been entered and is highlighted.
I managed to do that only with a timeout:
setTimeout(function() { $('.select2-results__option').trigger("mouseup"); }, 500);
So, the full solution would be this:
$('select').select2();
function select2_search ($el, term) {
$el.select2('open');
// Get the search box within the dropdown or the selection
// Dropdown = single, Selection = multiple
var $search = $el.data('select2').dropdown.$search || $el.data('select2').selection.$search;
// This is undocumented and may change in the future
$search.val(term);
$search.trigger('input');
setTimeout(function() { $('.select2-results__option').trigger("mouseup"); }, 500);
}
$('button').on('click', function () {
var $select = $($(this).data('target'));
select2_search($select, 'Arizona');
});