How to create searchable select box

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.

In this tutorial, I show how you create a dropdown with a search box using the select2 plugin and read the selected option.

In order to use Select2, you must include the compiled JavaScript and CSS files on your website. There are multiple options for including these pre-compiled files, also known as a distribution, in your website or application.

Step 1: First you need to adding jQuery to your web pages

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Step 2: Also include the following lines of code in the <head> section of your page:

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

Step 3: Now you need to create one select box

<select name="cars" id="cars" class="js-example-basic-single">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select> 

Step 4: In above code you must have to declare class=”js-example-basic-single” inside select box.

<script>
// In your Javascript
$(document).ready(function() {
    $('.js-example-basic-single').select2();
});
</script>

Full code as below

 <!DOCTYPE html>
<html>
<head>
<title>How to create searchable select box</title>
<!-- JS for jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- CSS for searching -->
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />
<!-- JS for searching -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>

<script>
// .js-example-basic-single declare this class into your select box
$(document).ready(function() {
    $('.js-example-basic-single').select2();
});
</script>
</head>
<body>

<h1>How to create searchable select box</h1>

<label for="cars">Choose a car:</label>

<select name="cars" id="cars" class="js-example-basic-single">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select> 

</body>
</html> 


Related Posts

Divyesh Patel

I'm Divyesh Patel, Web & App developer. I want to make things that make a difference. With every line of code, i strive to make the web a beautiful place.

Leave a Reply