Hi! In this post let's see how to create drop down list with search using jQuery. With dropdown list you can easily control what user inputs, but what if the drop down combo contains long list of values to skim through. Say you have a drop down containing country names (which is huge), wouldn't it be nice to provide a search box to easily narrow down the choice? That's what we are going to do here. Create a searchable drop down list in jquery!
jQuery Drop Down List with Search Box
There is no need to reinvent the wheel. There's already a nice jquery library named Select2 is available for creating searchable dropdown which we are going to use in our example. Select2 library will add a search box to html drop down list which is easily customizable. It supports searching, tagging, remote data sets, infinite scrolling and many other handy options.
The library is available in CDN. But if you want it locally then download it from here and use it.
This is the simple script for adding a search box to dropdown combo box using select2 library.
Searchable Dropdown Script
<!DOCTYPE html> <html> <head> <title>jQuery Drop Down List with Search Box Example</title> <script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script> <link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/css/select2.min.css" rel="stylesheet" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2-rc.1/js/select2.min.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function() { var cnames = ["Argentina", "Australia", "Austria", "Bangladesh", "Belgium", "Brazil", "Canada", "China", "Denmark", "Dominica", "Dominican Republic", "France", "Germany", "Hong Kong", "India", "Indonesia", "United Arab Emirates", "United Kingdom", "United States"]; $("#country").select2({ data: cnames }); }); </script> <style> #country { width: 300px; } </style> </head> <body> <h1>Select Country</h1> <select id="country"></select> </body> </html>
Above script will create a searchable drop down list like this.
jQuery Searchable Drop Down List |
You can either scroll through the list or start typing in the search box for the choices to pop up under the box.
Read Also:That's all about creating drop down list with search using jquery.
No comments:
Post a Comment