0

I use Select2 as an auto suggest. That means, I fetch options from a remote source via ajax. This works perfectly.

Now, the customer wants to have all options loaded before he starts typing. That kind of defeats the purpose of an auto suggest, but if he wants it that way, he shall have it.

Anyways, I would need to display the first 50 or 100 elements before the user starts typing and after the third typed character the Select2 input should fetch the options again.

I tried prepopulating the select with option values (for example "aa","bb" and "cc"), but it only displays the placeholder. Is it possible to send a request as soon as the user clicks on the select? That would be a possibility too, since the remote source could send back the first 50 results. If anyone could steer me in the right direction, I would be thankful :)

2
  • I've never used Select2 but I've just read the documentation and I would try this: 1 - define select as array with the first 50 or 100 elements. see here 2 - redefine the select on onkeydow/up event, with the remote option using minimumInputLength: 3. Hope it helps. Commented Oct 13, 2016 at 14:36
  • Thanks for the comment @Elmer Dantas, this could actually work in a way. It seems just less of a hassle to use another autocomplete script though :) Commented Oct 13, 2016 at 16:44

1 Answer 1

0

A quick workaround if anyone will have the same issue:

  1. set the "minimumInputLength" to 0. This way a request will be sent as soon as the user opens the Select2 input element. The search parameter will of course be an empty string.

  2. in the "processResults" function add a logic to allow pagination. The returned object needs a "pagination" property with a boolean member called "loadMore". You can read more about that here: https://stackoverflow.com/a/29022107/430997 This way you just enabled infinite scrolling. Of course you need support for paginated results on the serverside too.

  3. Optionally you can fetch sources from different locations. The "url" parameter of the ajax option can be a function. If you want to call different endpoints based on the number of characters (mostly to check, if the number of characters is 0), you can check for it inside the url function and return the appropriate endpoint.

This is just a workaround and only simulates initial values. If anyone has a real answer to my question, please post it :)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.