Level of expertise: Beginner, Intermediate
This POC is intended to illustrate Select2, a JQuery Plugin which is used as a replacement for select box with support for searching, tagging, remote data sets, infinite scrolling and many other highly used options and contains event handling.
The sample project explains basic usage of select2 with examples to handle both client and remote data.
Select2 plugin can be used in different environments. I created a sample project with the following development environment.
Development Environment Used:
- JDK 7.0_60
- Tomcat v7.0
- Eclipse Java EE IDE
Simple steps to create a select2 box
Include the following code in the head section of html page or download the same file and then specify the path in order to use the select2 plugin
- <link href=”//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css” rel=”stylesheet” />
- <script src=”//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js”></script>
Whichever ‘select’ element we want to convert as select2, the following line will do the trick
Steps to implement select2 in the project:
- Create a dynamic web project in the eclipse with the project structure as shown below.
2. Create an html page index.html, include the jQuery and select2 source files.Then include the code for select tag with id as below.
Choosing a Global Software Development Partner to Accelerate Your Digital Strategy
To be successful and outpace the competition, you need a software development partner that excels in exactly the type of digital projects you are now faced with accelerating, and in the most cost effective and optimized way possible.
Get the Guide
3. Create a select.js file. Include the following code to convert example1 select tag as select2 box.
The above code loads the select box with options given in the data attribute. Here array of data is set in the data attribute. The ‘allowClear’ attribute set to true is used to clear the selection. We can select multiple choices by setting attribute ‘multiple’ to true. Placeholder is used to show caption in the text box. Formatting the display text is easier in select2 plugin. We can search the text in the select box match with the options. For example, if we key ‘sing’, the option match with ‘Singapore’ will be fetched easily.
The output is as follows.
4. Loading Remote Data
Fetching remote data from server and loading into select box is much easier in select2. The below code converts the example2 select box as select2 by loading the remote data. The code uses ajax method which provides built in support in select2 plugin.
For illustration purpose, included json format data in the ‘ajax.json’ file directly and used in the url attribute. Configure the path of the data returned from the server in the url attribute.
The output is
Thus this plugin is more useful in handling combo component than normal html select tag.