Jquery Select2
Jquery Select2
#jquery-
select2
Table of Contents
About 1
Remarks 2
Versions 2
Examples 2
Chapter 2: Loading remote data into Select or DropDown box using Search option 5
Introduction 5
Examples 5
Introduction 10
Examples 10
Credits 11
About
You can share this PDF with anyone you feel could benefit from it, downloaded the latest version
from: jquery-select2
It is an unofficial and free jquery-select2 ebook created for educational purposes. All the content is
extracted from Stack Overflow Documentation, which is written by many hardworking individuals at
Stack Overflow. It is neither affiliated with Stack Overflow nor official jquery-select2.
The content is released under Creative Commons BY-SA, and the list of contributors to each
chapter are provided in the credits section at the end of this book. Images may be copyright of
their respective owners unless otherwise specified. All trademarks and registered trademarks are
the property of their respective company owners.
Use the content presented in this book at your own risk; it is not guaranteed to be correct nor
accurate, please send your feedback and corrections to info@zzzprojects.com
https://riptutorial.com/ 1
Chapter 1: Getting started with jquery-select2
Remarks
This section provides an overview of what jquery-select2 is, and why a developer might want to
use it.
It should also mention any large subjects within jquery-select2, and link out to the related topics.
Since the Documentation for jquery-select2 is new, you may need to create initial versions of
those related topics.
Versions
Examples
Jquery - Select2 Installation and Setup
1. Directly using CDN's in your project under the head section of your project.
link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css"
rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"/>
2. Download the code to your local machine and include it into your project. it should look like
https://riptutorial.com/ 2
this
Then include these lines into head section of your html page
Note: You need to have Jquery included into your project for Select2 to work correctly.
PITFALL: if Current version of jquery and Select2 are conflicting or Select2 features
are not working. Then move the select2 variables and implementations in separate
block of document body $(document).ready(function () { //your select2 code ..... });
<select id="select2_example">
<option>Test</option>
</select>
Approach1:
Approach2:
<script type="text/javascript">
$('select').select2();
</script>
Please note that using this approach all the defined 'select' control of page will inherit
features of Select2. If you only want to use Select2 for certain controls then skip this
step and write your own code to use select2 feature directly and jquery/javascript
feature separately for other select control. However, you can use the value of
manipulated through Select2 for Jquery or vice-versa.
Further examples of 'The Basics' can be found in the Select2 GIT documentation here
Select2 GIT project is here. Please go through the Select2 Github site for detail feature of this
product.
https://riptutorial.com/ 3
In order to clear the selection of those values which are selected using a Select2 drop down,we
can use the empty() function.
<select id="select2_example">
<option>Option1</option>
<option>Option2</option>
<option>Option3</option>
</select>
$("#select2_example").empty();
$("#select2_example").select2("val", "");
https://riptutorial.com/ 4
Chapter 2: Loading remote data into Select or
DropDown box using Search option
Introduction
When the record count is too high , loading all records at once can make application slow in
addition user will not like the idea of scrolling thousand of records to find what he is looking for. Its
better to give user a power search and filter the records as he types the character.
Examples
Creating searchable Dropdown / Select box using Jquery - select2 in C# MVC
This example will demonstrate the searchable select box in MVC. it uses Ajax to get all records
from database as user types the new character. I'll consider Country and its City example to
illustrate the functionality of Searchable dropdown box. Code behind is c# with MVC, but its easy
to grasp whole concept.
First I have created a basic background in step wise manner. Last steps is Select2 jqery method
which execute this code.
Step 1: Declare DropDownListFor control in razor. It creates Select box in HTML mark up.
Hidden variable Value field also contains razor library method url.action. it has two parameters.
First parameter, GetAutoCompleteSearchSuggestion is C# method, which is the entry point at
server side for Ajax call to fetch the records. Second parameter is controller name "Country".
<h2>
<label>@Html.LabelFor(m => m.ddlCountry)</label>
@Html.DropDownListFor(m => m.ddlCountry, Model.Station, new { @class =
"select2Style" })
</h2>
Step 2: These are Predefined CSS class available for Select box. You can customized the control
using these classes. In addition you can add your own css class for controls.
/* Input field */
.select2-selection__rendered { font-size:medium; font-weight:normal; }
https://riptutorial.com/ 5
/* Search field */
.select2-search input { font-size:medium; font-weight:normal; }
/* Each result */
.select2-results {
font-family: Arial, Helvetica, sans-serif;
font-size: medium;
font-weight:normal;
/* Selected option */
.select2-results__option[aria-selected=true] {
background: #3ea211;
font-family: Arial, Helvetica, sans-serif;
font-size:medium;
font-weight:normal;
}
/* My css class*/
.select2Style {
width:200px;
}
Step 3: Create the Model. Note that same variable name is in razor declaration.
[Display(Name = "Country:")]
public string ddlCountry { get; set; }
public IEnumerable<SelectListItem> Country { get; set; }
Step 4: Create "Country" Controller and C# method which will be called by jquery ajax method
every time user enters a text in searchable dropdown's textbox.
try
{
suggestions = GetCountryList( queryParameters.query);
}
catch (Exception Ex)
{
ErrorMessage = Ex.Message;
return Json(ErrorMessage);
}
return Json(suggestions.Select(c => new { Name = c.Value, ID = c.Key }).ToList(),
JsonRequestBehavior.AllowGet);
}
Step 5: Set the database query and operation to fetch records. it gets the list of country. please
note the db query, it affects the way item for dropdown is fetched and displayed. you'll have to
https://riptutorial.com/ 6
customize your query to fetch the result according to your requirement.
if (reader.HasRows)
{
while (reader.Read())
{
countryId = reader[0].ToString();
countryValue = reader[1].ToString();
ddlcountryDictionary.Add(countryId, countryValue);
}
}
}
catch (Exception ex)
{
Step 6: Jquery function will list country name starting with the entered text by user, if user select
"a" then all country with starting with name "a" will be listed and next if user types "n" then
country name not starting with "an" will be filtered out.
$("#ddlCountry").select2({
ajax: {
url: $("#ajaxUrlGetAutoCompleteSearchSuggestion").val(),
data: function (params) {
var queryParameters = {
//restrictedCountry: $("#resCountry").val(), // pass your own parameter
https://riptutorial.com/ 7
dataType: "json",
cache: true,
delay: 250,
//type: 'POST',
contentType: "application/json; charset=utf-8",
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: $.map(data, function (val, item) {
return { id: val.ID, text: val.Name };
}),
// if more then 30 items in dropdown, remaining set of items will be show
on numbered page link in dropdown control.
pagination: { more: (params.page * 30) < data.length }
};
}
},
minimumInputLength: 1 // Minimum length of input in search box before ajax call
triggers
});
Cascading DropDown for country's city name. This method will be called by Jquery when user is
done with country selection in parent dropdown. I have followed MVC concept and provided the
basic approach for cascading dropdown.
Ajax will call GetCityName method on code behind on Server and received information is
recursively used to create City dropdown.
https://riptutorial.com/ 8
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
}
});
});
Read Loading remote data into Select or DropDown box using Search option online:
https://riptutorial.com/jquery-select2/topic/10830/loading-remote-data-into-select-or-dropdown-box-
using-search-option
https://riptutorial.com/ 9
Chapter 3: Select2 Uses
Introduction
Select never work in Bootstrap Modal follow given steps to use select2 in Bootstrap Model.
Examples
Using Select2 in a Bootstrap Modal/PopUp
If you are using Bootstrap Modal then be sure that Model tabindex=-1 is removed.
$('#targetId').select2({
width: '100%',
dropdownParent: $("#myModal")
})
Using Select2 in a Bootstrap Modal/PopUp If you are using Bootstrap Modal then be sure that
Model tabindex=-1 is removed.
https://riptutorial.com/ 10
Credits
S.
Chapters Contributors
No
https://riptutorial.com/ 11