Select2 is one of the best user interface enhancers I have come across – if you do not know what it is then you need to go play with it.
It transforms SELECT boxes into dynamic, stunning, interactive UI elements and allows for all sorts of customizations and developer fun.
What I want to be able to do is select items from different categories within the select2 box and then add an icon displaying to the user which category they came from. In this article I will show how.
Example
I want to take this
turn it into this with a type ahead
And when a user selects the items – make this based on the category selected
And it is really pretty simple and straightforward.
The Code
We start with our select box
<select style="width:500px" id="vehicle" multiple="multiple"> <optgroup label="Cars"> <option class="car">Honda</option> <option class="car">Toyota</option> <option class="car">Ford</option> <option class="car">GM</option> </optgroup> <optgroup label="Bikes"> <option class="bike">Harley Davidson</option> <option class="bike">Kawasaki</option> <option class="bike">Aprilia</option> <option class="bike">Ducati</option> </optgroup> </select>
and then we add our select2 code
$("#vehicle").select2().on("change", function(e) { if (e.added) { var icon = "" $('.select2-search-choice DIV').filter(function() { icon = '<img src="images/'+e.added.css+'.png"/> '; return $(this).text() == e.added.id; }).prepend(icon); } })
So what this does is:
- select the #vehicle DOM element
- turn it into a Select2 plugin control
- When the control is changed and if an element is added
- Find the DIV which has been created to display the new item
- We use filter based on the newly added.id to make sure we only get the one just created
- create the HTML for the appropriate icon based on the class of the selected item
- prepend that icon HTML inside of the DIV containing the newly selected option
Conclusion
I have barely scratched the surface of what is possible with Select2. But I hope that you can see with only 9 lines of code we have significantly improved a user experience 🙂
I love Select2 and the options are endless
Enjoy 🙂
That’s a cool example, and I agree: Select2 is awesome!
Did you know that Select2 is part of the Bootstrap4XPages plugin? Demos here: http://www.bootstrap4xpages.com/bs4xp/demos.nsf/Bootstrap_Select2.xsp
Hey Mark – thanks for the comment 🙂
I did actually but I expect a number of people don’t – thanks for the link 🙂