Posted about 1 month ago. Visible to the public. Linked content.

Howto: Select2 with AJAX

Select2 comes with AJAX support built in, using jQuery's AJAX methods.
...
For remote data sources only, Select2 does not create a new element until the item has been selected for the first time. This is done for performance reasons. Once an has been created, it will remain in the DOM even if the selection is later changed.

If you have a huge collection of records for your select2 input, you can populate it via AJAX in order to not pollute your HTML with lots of <option> elements.

All you have to do is to provide the collection in the Select2 data format and extend the input with ajax options. You should paginate your results on server side to reduce the load. Select2 supports an "infinite scroll" feature, which will be enabled with a params.page property in the request and a pagination.more value in the response.

I would also recommend to use the minimumInputLength option to not fire your first request on opening the input element.

The Select2 data format

Copy
{ "results": [ { "id": 1, "text": "Option 1" }, { "id": 2, "text": "Option 2" } ], "pagination": { "more": true } }

Basic ajax options

Copy
$('#mySelect2').select2({ ajax: { url: <url-to-your-source>, data: function (params) { return { query: params.term, page: params.page || 1 } } processResults: function (data, params) { return data }, } });

Further reading: https://select2.org/data-sources/ajax

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Florian Leinsinger
Last edit:
about 1 month ago
by Florian Leinsinger
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Florian Leinsinger to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more