Mandala   / / / / / / / / / / / /   / / / / / / / / / / / /   / / / / / / / / / / / /   / / / / / / / / / / / /   / / / / / / / / / / / /   / / / / / / / / / / / /   / / / / / / / / / / / /  + + + + + +  + + + + + +  + + + + + +  + + + + + +  + + + + + +  + + + + + +  + + + + + +{ { {} } } }  { { {} } } }  { { {} } } }  { { {} } } }  { { {} } } }  { { {} } } }      ../../    ../../    ../../    ../../    ../../    ../../    ../../ <></><></><></> <> </><></><></> <> </><></><></> <> </><></><></> <> </><></><></> <> </>

How To Create a Dynamic Select Box With the Select2 Library

This tutorial demonstrates using a Select2 JavaScript library to create single and multi-select boxes on a web page, with code and examples.

We will learn how to build select boxes with the select2 jquery library in a form on a web page. In addition, we will talk about why the select2 library was included in the project and what benefits it provides. By the end of this tutorial, you will be tooled with the knowledge to create a select element for your web page using jQuery and HTML. All the complete code will be located at the end of the tutorial, with code examples and steps shared.

What Is the Select2 Library?

The select2 library provides web developers with tools for searching, tagging, adding remote datasets, infinite scrolling, etc. It is a jQuery plugin that offers a customizable select element framework with support for many features. The jQuery plugin supports more than 40 spoken languages and is a fast and effective list search using ajax. Additionally, a Select2 jQuery form element can be shaped entirely with CSS and Bootstrap according to user requests and allows dynamic element creation that supports modern and old web browsers.

Integration of Select2 in websites is widespread, especially in forms created across the web, thanks to a search feature using <select> and multiple option support using <option> backed with JavaScript.

Installation

Select2 does not require much work to set up when used within an HTML page. Using a CDN is recommended to install Select2. Place two elements, a script, and a link, between the <head> tags in the HTML to use this library with the URL to the CDN file locations.

<!-- CSS Library -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />

<!-- JavaScript Library -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

However, the files compiled from GitHub should be downloaded if manual installation is required. Downloaded files should also be added to the page using a <link> and <script> elements with the URL of the file’s location on a server.

<!-- CSS Library -->
<link href="path/to/select2.min.css" rel="stylesheet" />

<!-- JavaScript Library -->
<script src="path/to/select2.min.js"></script>

This project will also include bootstrap to help structure the page. Now that we’re done with the setup process, it’s time to dig into a little more detail.

What Is Select2 Used For?

Select2 is used to upgrade native HTML, giving you a customizable select box input with additional features. Features include dynamic item creation, theming, remote data (For example, a JSON API, database, or JavaScript array), infinite scrolling, tags, searching, and multiple choices.

What is a Select2 Dropdown?

By default, Select2 will provide a dropdown that displays search text data retrieved from a dataset, list item array, or an options element. Results will be positioned “absolutely” to appear below or above a search selection container, and each result within the dropdown will be selectable as an option.

How Does Select2 Search Work?

Whenever users type in search terms in the search box of a Select2 input, it uses an internal regex matcher to search for results, closely related text, or an exact phrase. Results are then churned out into a dropdown box for selection. You can also customize the matcher configuration by supplying a JavaScript callback function that can match results in new ways.

How To Create Select2 Element?

In simple instructions, a Select2 element can be created by initializing the jQuery library against the desired form select element.

// Initilizing the library.
$('#someSelectElement').select2();

How To Create a Basic Select Element With Select2

After the installation, two operations are required to apply select2 to a select form element. Let’s take a quick look at what we need to do.

First, let’s create the structure of a select input box using HTML and bootstrap, as demonstrated in the code below. Content for the options of the input element we will be making will be based on trend research topics.

HTML

<div class="col-md-4">
  <form>
    <label>Trend Research Topics Basic Select</label><br>
    <select id=”myFirstSelect2Basic” class="form-control" name="topics">
      <label>Trend Research Topics</label>
      <option value="1">Machine Learning</option>
      <option value="2">Deep Learning</option>
      <option value="2">Reinforcement Learning</option>
      <option value="3">Web 3.0</option>
      <option value="4">Metaverse</option>
      <option value="5">Augmented Reality</option>
      <option value="6">Mixed Reality</option>
      <option value="7">Industry 5.0</option>
    </select>
  </form>
</div>

After completing the first step, we need to call select2 within JavaScript. Calling select2 can also be done in a separate name.js file (An example JavaScript code file).

To call the Select2 library, we need to use the id of the select box we created above and place the id inside a jQuery selector.

$('#myFirstSelect2Basic')

Once we have included the JavaScript selector, our HTML element is initialized with a Select2 function and is now ready for use.

JavaScript

<script>
  $(document).ready(function() {
    $('#myFirstSelect2Basic').select2();
  });
</script>

Moving on to the HTML, we need to combine all the components and make a complete web page with our new form element.

Full Code:

<!DOCTYPE html>
<html>
   <head>
      <title>Select2 Basic Example</title>
      <!-- Bootstrap-->
      <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
      <!-- Select2 -->
      <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
   </head>
   <body>
      <div class="col-md-4">
         <form>
            <label>Trend Research Topics Basic Select</label><br>
            <select id="myFirstSelect2Basic" class="form-control" name="topics">
               <label>Trend Research Topics</label>
               <option value="1">Machine Learning</option>
               <option value="2">Deep Learning</option>
               <option value="2">Reinforcement Learning</option>
               <option value="3">Web 3.0</option>
               <option value="4">Metaverse</option>
               <option value="5">Augmented Reality</option>
               <option value="6">Mixed Reality</option>
               <option value="7">Industry 5.0</option>
            </select>
         </form>
      </div>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
      <script>
         $(document).ready(function() {
           $('#myFirstSelect2Basic').select2();
         });
      </script>
   </body>
</html>

The output of the code:

Creating a Basic HTML Select Box With Select2 Library
Creating a Basic HTML Select Box With Select2 Library

How To Create a Multi-Select Element With Select2

The operations we performed above using Select2 are also valid for multiple input boxes. The only difference is that since there will be more than one selection, we will need to add a “multiple” attribute to the select element. Additionally, we will need to create an array in the input using name=topics[ ] as another attribute (for more than one selection in an input element).

name="topics[]" multiple="multiple"

Once we’ve added the new attributes, we can look at the following code and render a multi-select box created with Select2.

Full Code:

<!DOCTYPE html>
<html>
   <head>
      <title>Select2 Multiple Example</title>
      <!-- Bootstrap-->
      <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
      <!-- Select2 -->
      <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
   </head>
   <body>
      <div class="col-md-4">
         <form>
            <label>Trend Research Topics Multiple Select</label><br>
            <select id="myFirstSelect2Multiple" class="form-control" name="topics[]" multiple="multiple">
               <label>Trend Research Topics</label>
               <option value="1">Machine Learning</option>
               <option value="2">Deep Learning</option>
               <option value="2">Reinforcement Learning</option>
               <option value="3">Web 3.0</option>
               <option value="4">Metaverse</option>
               <option value="5">Augmented Reality</option>
               <option value="6">Mixed Reality</option>
               <option value="7">Industry 5.0</option>
            </select>
         </form>
      </div>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>
      <script>
         $(document).ready(function() {
           $('#myFirstSelect2Multiple').select2();
         });
      </script>
   </body>
</html>

The output of the code:

How to Create a Multi-Select Box Using the Select2 Library
How to Create a Multi-Select Box Using the Select2 Library

Codepen Example

You can use the shared CodePen links to create a select box element with the Select2 jQuery library.

For basic Select2:

You can edit code for the basic select2 input on codepen.io.

For multiple Select2:

The multi-option select2 input can be found on codepen.io and edited for your purpose.

Final Words

Select2 JavaScript library is an essential jquery plugin for web forms and is widely used across the web. Using the library provides great convenience, especially when there are too many options for a select input (For example, city, job, hobby, etc.) or when choosing more than one item. For these reasons, it should be used to positively increase a user’s experience on a website or page. Otherwise, navigation can be more challenging for users when the select box element is built using native HTML with many options.

Recommended Articles

Other Articles