Skip to main content


Introduction to jQuery select2 plugin

Level of expertise: Beginner, Intermediate

Prerequisite: JQuery/JavaScript


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:

  1. JDK 7.0_60
  2. Tomcat v7.0
  3. Eclipse Java EE IDE
  4. jquery-1.11.1.min.js
  5. select2-4.0.0.min.js

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

  1. <link href=”//” rel=”stylesheet” />
  2. <script src=”//”></script>

Whichever ‘select’ element we want to convert as select2, the following line will do the trick

  1. <script type=”text/javascript”>
  2. $(‘select’).select2();
  3. </script>

Steps to implement select2 in the project:

  1. 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.


   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.



Ajax.json file


The output is


Thus this plugin is more useful in handling combo component than normal html select tag.





Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Kavitha Shanmugam

More from this Author

Follow Us