In this chapter, we will learn how to use JS/CSS to implement the drop-down menu search or filter function.
First look at the effect as follows:
View online examples: Try It!
HTML Codes
Example
<div class="dropdown"> <button onclick="myFunction()" class="dropbtn">Drop-down Menu</button> <div id="myDropdown" class="dropdown-content"> <input type="text" placeholder="Search.." id="myInput" onkeyup="filterFunction()"> <a href="#about">Google</a> <a href="#base">TutorialFish</a> <a href="#blog">Bing</a> <a href="#contact">Yahoo</a> <a href="#custom">EBay</a> <a href="#support">Facebook</a> <a href="#tools">Twitter</a> </div> </div>
CSS Codes
The following styles of search search box and association menu:
Example
/* drop-down menu button */ .dropbtn { background-color: #04AA6D; color: white; padding: 16px; font-size: 16px; border: none; cursor: pointer; } /* Move the mouse to the drop-down menu button to the style*/ .dropbtn:hover, .dropbtn:focus { background-color: #3e8e41; } /* search bar */ #myInput { box-sizing: border-box; background-image: url('searchicon.png'); background-position: 14px 12px; background-repeat: no-repeat; font-size: 16px; padding: 14px 20px 12px 45px; border: none; border-bottom: 1px solid #ddd; } /* The style of the search box to get the focus */ #myInput:focus {outline: 3px solid #ddd;} /* Container <div>-Position the drop-down menu */ .dropdown { position: relative; display: inline-block; } /* Drop-down menu content (hidden by default) */ .dropdown-content { display: none; position: absolute; background-color: #f6f6f6; min-width: 230px; border: 1px solid #ddd; z-index: 1; } /* Drop-down menu link style */ .dropdown-content a { color: black; padding: 12px 16px; text-decoration: none; display: block; } /* Move the mouse to the style of the link */ .dropdown-content a:hover {background-color: #f1f1f1} /* Show the drop-down menu (use JS to add the .dropdown-content class) */ .show {display:block;}
JavaScript Codes
The following is the JavaScript code for searching the search box and the association menu:
Example
/* Click the button to set the display and hide of the drop-down menu */ function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } /* Search function */ function filterFunction() { var input, filter, ul, li, a, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); div = document.getElementById("myDropdown"); a = div.getElementsByTagName("a"); for (i = 0; i <a.length; i++) { txtValue = a[i].textContent || a[i].innerText; if (txtValue.toUpperCase().indexOf(filter)> -1) { a[i].style.display = ""; } else { a[i].style.display = "none"; } } }