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 not allows you to search whole or particular string.

Searching is required on the list when there is a long list of items 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 search box using the select2 plugin and read the selected option.

1. Download and Include

  • Download select2 library from GitHub.
  • Include select2.min.css and select2.min.js with jQuery library in <head> section.
<!-- Script -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src='select2/dist/js/select2.min.js' type='text/javascript'></script>

<!-- CSS -->
<link href='select2/dist/css/select2.min.css' rel='stylesheet' type='text/css'>
 

2. HTML

Create a dropdown element and added some options. Also created a button to read selected dropdown option and display 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 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);

  });
});
 

5. Conclusion

I hope this tutorial, helps you to create dropdown element with search box using select2 plugin.
You can also populate data in select2 dropdown with AJAX.

I already have written a tutorial on this which you can view it here.

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

CONVERSATION

0 Comments:

Post a Comment

Back
to top