How do i search options via javascript

Is there a way to search select2 options by label via javascript.
Like:
$(’#id’).select2(‘search’,‘text’);

Select2 doesn’t provide a programmatic search capability. You can do it manually, though, by setting the value of the Select2’s input field to the search term you want. Something like this will work:

$("#mySelect").select2("open");
$("input.select2-search__field").eq(0).val(searchTerm).trigger("input");

The first line programmatically opens the the Select2, exposing the search field. The second line sets the value of the search field to the desired search term and triggers the input event, which causes the Select2 to display the items that match the value of searchTerm.

2 Likes

I’ve been using this trick for a few months to search for a domain in a select2 dropdown when a user enters an email, but now it focuses the Select2 search input field which isn’t the behaviour I’m after. Still hunting for a solution. Don’t know what the old version was, but the new behaviour is in 4.0.13.