This code creates a user-friendly dropdown menu with a search box using Bootstrap 5 and the Bootstrap-Select plugin. The plugin adds advanced features to the standard dropdown, making it easier for users to find and select items.
The menu supports live searching, allowing users to filter options quickly. This is particularly useful for forms with many options, improving the overall user experience.
Powered by Bootstrap and jQuery libraries, this feature ensures compatibility and smooth performance. This code is ideal for adding searchable dropdown menus to modern web applications.
How to Create Bootstrap 5 Select Dropdown with Search Box
1. First, include the necessary Bootstrap and Bootstrap-Select CSS files in the <head>
section of your HTML document to style the dropdown:
<!-- Bootstrap 5 CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous"> <!-- Bootstrap-select CSS --> <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta2/css/bootstrap-select.min.css" rel="stylesheet">
2. Next, add a <select>
element with the selectpicker
class to create the dropdown menu. The data-live-search="true"
attribute enables live search functionality.
<div class="container mt-5"> <h2>Select Dropdown with Search</h2> <select class="selectpicker" data-live-search="true"> <option data-tokens="ketchup mustard">Hot Dog, Fries and a Soda</option> <option data-tokens="mustard">Burger, Shake and a Smile</option> <option data-tokens="frosting">Sugar, Spice and all things nice</option> <option data-tokens="fries">Hot Dog, Fries and a Soda</option> <option data-tokens="burger">Burger, Shake and a Smile</option> <option data-tokens="soda">Sugar, Spice and all things nice</option> </select> </div>
3. Before the closing </body>
tag, add the required JavaScript libraries for Bootstrap and Bootstrap-Select to enable functionality:
<!-- Bootstrap JS Bundle (includes Popper) --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script> <!-- jQuery (required by bootstrap-select) --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <!-- Bootstrap-select JS --> <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.14.0-beta2/js/bootstrap-select.min.js"></script>
4. Finally, initialize the Bootstrap-Select plugin with jQuery to enable the search functionality for the dropdown:
(function() { $('.selectpicker').selectpicker(); })(jQuery);
That’s all! hopefully, you have successfully created the Select Dropdown with Search Box on your website. This feature enhances usability, especially in forms with a large number of options. If you have any questions or suggestions, feel free to comment below.