Make a Dropdown with Search Box using jQuery

You already know that in HTML there is no search option in the dropdown element.

When you press any single key in the dropdown then it takes you to the option but does not allow you to search whole or particular string.

Searching is required on the list when there is a long list of items that are available.

It is time-consuming to find the option by scrolling the list.

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

Make a Dropdown with Search Box using jQuery


Contents

  1. Download and Include
  2. HTML
  3. jQuery
  4. Demo
  5. Conclusion

1. Download and Include

  • Download select2 library from GitHub.
  • Include select2.min.css and select2.min.js with jQuery library in <head> section.
<!-- Select2 CSS --> 
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" /> 

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

<!-- Select2 JS --> 
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>

2. HTML

Create a dropdown element and added some options. Also created a button to read selected dropdown option and display them in <div id='result'>.

Completed Code

<!-- Dropdown --> 
<select id='selUser' style='width: 200px;'>
     <option value='0'>Select User</option> 
     <option value='1'>Yogesh singh</option> 
     <option value='2'>Sonarika Bhadoria</option> 
     <option value='3'>Anil Singh</option> 
     <option value='4'>Vishal Sahu</option> 
     <option value='5'>Mayank Patidar</option> 
     <option value='6'>Vijay Mourya</option> 
     <option value='7'>Rakesh sahu</option> 
</select>

<input type='button' value='Seleted option' id='but_read'>

<br/>
<div id='result'></div>

3. jQuery

Initialize select2() on <select id='selUser'> and define click event on the button to read the selected option text and value.

Display the values in <div id='result'>.

Completed Code

$(document).ready(function(){
 
    // Initialize select2
    $("#selUser").select2();

    // Read selected option
    $('#but_read').click(function(){
        var username = $('#selUser option:selected').text();
        var userid = $('#selUser').val();

        $('#result').html("id : " + userid + ", name : " + username);

    });
});

4. Demo

View Demo


5. Conclusion

I hope this tutorial, helps you to create a dropdown element with a search box using a select2 plugin.

If you want to know how to load data using AJAX in select2 then you can view this tutorial.

If you found this tutorial helpful then don't forget to share.