We all used Select2. We all depended on it for a long time, for all our Select/Autocomplete needs. But it’s been showing signs of aging for quite a while, and it’s one of the last libraries that still keeps me tied to jQuery.
Tom Select was forked from selectize.js with the goal of modernizing the code base, decoupling from jQuery, and expanding functionality.
Well, that looks good to me.
And since it was renovating time, I also decided to consolidate all that JS used to make Select2 work with Ajax, filtering, etc. in a few Stimulus controllers.
All the examples shown here are coded with a Rails app in mind, but they can easily be adapted for any other stack.
The simple case
I wanted to make it as simple as possible to use the solution from the HTML code. The simplest solution would be just adding a data-controller to a select tag.
So, I installed tom-select and created a ts--select controller, using the new generator from stimulus-rails:
I just imported TomSelect and created the instance on connecting
It worked like a charm! For simple cases, when all you need is a select/options backed solution, that is all it takes.
Autocomplete with Ajax
Sometimes, when your list is too large, you may prefer a remote approach.
Keeping simplicity in mind, I wanted something like:
The remote endpoint only needs to return a JSON Array with the matching results.
Thanks to Tom Select’s support for remote data and using the handy @rails/request.js, the actual implementation ended up quite straightforward.
Filtering other Select
Another very common use case is the need to filter the options of a select based on the selected value of another one. In this case, our controller has to include both selects. The markup I imagined for such a task would be something like:
Again, the remote endpoint returns the filtered results
The stimulus controller is somewhat similar to the previous one, but with enough differences to require a new one
It checks for a selected value every time the State changes and on connecting. Then it fetches or clears the results accordingly.
Tom Select is a very useful library to implement advanced behaviour in select tags, and can replace select2 with advantages. We’ve seen examples of 3 different scenarios. Using Stimulus allows us to implement advanced funcionalities in the select, while keeping the html simple and enabling reuse of the code across different pages.