On open, is it possible show options from ajax data source without typing anything?

Hello,

Below is my current implementation of select2:

javascript:

  $('#product-code').select2({
        tags: true,
        ajax: {
            url: currentUrl + "api/INV_API/productCodesSelect2",
            data: function (params) {
                return {
                    q: params.term, // search term

                };
            },
            dataType: 'json',
            type: "GET",

            processResults: function (data) {
                return {
                    results: $.map(data, function (obj) {
                        return { id: obj, text: obj };
                    })
                };
            }


        },
        placeholder: "",
        selectOnClose: true,
        allowClear: true,
        minimumInputLength: 1,

    });

c# backend for search:

    [Route("api/INV_API/productCodesSelect2")]
    public IQueryable<string> GetDistinctProductCodesSelect2([FromUri] string q)
    {
        if (q != null)
        {
            var query = (from i in db.INVs
                         where i.PROD.Contains(q)
                         select i.PROD).Distinct();

            return query;
        }
        else
        {
            var query = (from i in db.INVs
                         select i.PROD).Distinct();
            return query;

        }
    }

What I want to achieve now, I don’t know if possible, is upon click on the selectbox, all the options will appear, without typing in any search term. I tried changing minimumInputLength into 0. But I still have to key in something or press space on the input box, then the options will populate. Is a matter of the changing the data: function (params) { block in the javascript to achieve this effect?

Thanks for advice.

(Note: see my other reply below for a possibly easier way to do what you want—although it might not work at all. If it doesn’t, then my answer here should work.)

It’s not possible if you use the built-in AJAX feature to retrieve your content, because the AJAX request is only triggered when the user starts typing.

However, there’s no reason you must use the built-in AJAX feature. You could retrieve the data for the select yourself (e.g., via fetch(), or the older xmlHttpRequest object, or your framework’s AJAX feature). Just put the data into an object that implements the Select2 data format and pass it to the Select2 initializer. The only “downside” to this approach is that the Select2 widget will not show a “loading” indicator. But you could arrange to show one yourself (or a spinner, or whatever you want).

If you don’t have a lot of data in your backend, you could load it all as described above and then just use the search feature on the in-memory data. I’ve seen good response times doing filtering with up to several hundred items. If you do have a lot of data (say, 1,000 or more items), then you could use the built-in AJAX feature to retrieve the filtered data when the user starts typing, and just use the “manual AJAX” approach above to “initialize” the Select2 (in which case you should probably arrange to manually pull just the first “pageful” of records to initialize the Select2). Keep in mind that if you use the built-in AJAX feature, searches will be slower (since they have to go over the network), and you might want to debounce the user’s typing so the Select2 only sends a request once the user has paused typing for a period of time.

One other note: please make sure you’re sanitizing the user’s query term before you use it in your SQL query on the back end. You should use a PreparedStatement if possible, with a placeholder for the query term, rather than including the user’s query term directly in your SQL. Alternatively, you could sanitize the query term before passing it to your “GetDistinctProductCodesSelect2” method. Just remember to never trust external data (including user input) to be what you expect.

Alternative approach: This might be a bug, but I’ve been playing around with the AJAX example in the Select2 documentation, and I’ve found that if you type one character and then immediately backspace, your request will be sent even though there’s no input by the time the “delay” value (250ms in the example) passes.

Assuming that setting the value of the search box programmatically will also cause an AJAX query to be sent (and that’s a big assumption), you could listen for the “select2:open” event and code your event handler to set the search box value to something (say, “*”) that your back end will recognize as meaning “send all the data” (i.e., what your else block does in your C# code above), and then quickly remove that value so the search box appears empty. The Select2 API doesn’t have a method that lets you set the value of the search box, but you can “hack it” like so:

$("input.select2-search__field").eq(0).val(...);

This might be worth a try before you fall back to my previous response (which should work in any case).