Using HTML, CSS, and JavaScript/jQuery will allow you to develop a Bootstrap dropdown with search capability. Here is an illustration:
HTML:
<div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Select a fruit </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <input class="form-control search" type="text" placeholder="Search..."> <div class="dropdown-menu-inner"> <a class="dropdown-item" href="#">Apple</a> <a class="dropdown-item" href="#">Banana</a> <a class="dropdown-item" href="#">Orange</a> <a class="dropdown-item" href="#">Grape</a> </div> </div> </div>
CSS:
.dropdown-menu-inner { max-height: 200px; overflow: auto; } .dropdown-menu .search { margin: 5px; width: calc(100% - 10px); }
JavaScript/jQuery:
$(document).ready(function() { $(".dropdown-menu .search").on("keyup", function() { var value = $(this).val().toLowerCase(); $(".dropdown-menu-inner a").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); });
Explanation:
- In a div with the class “dropdown-menu-inner,” the HTML code produces a dropdown button and menu with an input box for the search function and a number of fruit alternatives.
- The dropdown menu’s maximum height is defined by the CSS code, which also gives the search input box some additional appearance.
- In response to user input entered into the search box, the JavaScript/jQuery code filters the dropdown selections by adding or deleting the “show” class. The filter function on the anchor tags within the div with class “dropdown-menu-inner” is used to do this.
This is just one method for using jQuery to build a Bootstrap dropdown with search. Several alternative approaches exist as well, based on your own requirements and tastes.