Searchable Dropdown using jQuery Select2

page1
Searchable dropdown is very important in web development when creating a form we use dropdown to select the values user need to select if the list is big it is mandate to have a search box to select the values.

In this we will discuss how to create search box dropdown using jQuery library and Select2 plugin.

1. Need to include Select2 plugin using CDN or direct download and include in header.

2. HTML Code for Dropdown

3. jQuery Code to make this Dropdown as Select2 Dropdown.

4. Result

1. Include Select2 :


Please go to the website given above that is Select2 website.

I will use CDN link to show demo.

Open Visual Studio Code and create index.html page.

HTML

jQuery : Add jQuery

<script src="https://code.jquery.com/jquery-3.5.1.min.js" ></script>

Include Select2 related CSS and jQuery

<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>

Page6



2. HTML Code for Dropdown: Add HTML Code for Dropdown to generate a dropdown.


<select id="SelExample" >
            <option>Delhi</option>
            <option>Hyderabad</option>
            <option>Vizag</option>
            <option>Kochi</option>
            <option>Anantapur</option>
            <option>Dharmavaram</option>
            <option>Bengaluru</option>
            <option>Lucknow</option>
            <option>Madurai</option>
          </select>

Page7



3. jQuery Code to make this Dropdown as Select2 Dropdown.

After body add script to add Select2 function to Dropdown based on id and then selected value button to display what is selected.


<script>
    $(document).ready(function(){
 
               // Initialize select2
               $("#SelExample").select2();
              
               // Read selected option
               $('#but_read').click(function(){
                 var username = $('#SelExample option:selected').text();
                 var userid = $('#SelExample').val();
              
                 $('#result').text("id : " + userid + ", name : " + username);
               });
    });
</script>

page8
Add Style Tag in head tag as below.

<style>
    #SelExample
    {
          width:200px;
    }
</style>

    
Page10


4. Result:

 
Browse the html file and see the output.

You will have searchable dropdown with selected value button after searching a value and selected. We use the code we shown in JavaScript to read the value.

Page 12

On click of selected Value result will update with selected value.

beng

CodePen Link:

Github Link:


There are many customizations we can do for this Select2 Dropdown visit Select2 website for more information.



Thanks for Reading.

Here are my Popular blogs.




Post a Comment

0 Comments