Create a Custom Input Dropdown Search Using JavaScript
The following example shows how to create a custom input dropdown search using javascript.
Live Demo
Example
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Create a Custom Input Dropdown Search Using JavaScript</title> <style> #dropdown { position: relative; display: inline-block; width:200px; } #dropdown input { position: absolute; width:100%; } #dropdown ul { position: absolute; margin: 0; padding: 0; top: 20px; left: 0; border: 1px solid #ccc; list-style-type: none; width:100%; } #dropdown ul li { padding: 2px 5px; cursor: pointer; } .hide { display: none; } .active { background-color: blue; color: white; } </style> </head> <body> <div id="dropdown"> <input type="text" id="searchInput"> <ul class="hide" id="dropdownList"> </ul> </div> <script> let fruits = ['Apple', 'Apricot', 'Avocado', 'Banana', 'Blueberry', 'Cherry']; let searchInput = document.querySelector("#searchInput"); let dropdownList = document.querySelector("#dropdownList"); let selectedIndex = -1; function filterItems(){ selectedIndex = -1; dropdownList.classList.remove("hide"); let query = searchInput.value.toUpperCase(); let filteritems = fruits.filter(row => row.toUpperCase().includes(query)); let li = ""; filteritems.forEach((row, index) => { li += `<li onClick='selectRow(${index})' class=''>${row}</li>`; }); dropdownList.innerHTML = li; } searchInput.addEventListener("input", (ele) => { filterItems(); }); searchInput.addEventListener("focus", (ele) => { filterItems(); }); searchInput.addEventListener("keydown", (ele) => { let rows = dropdownList.querySelectorAll("li"); if (ele.key == 'ArrowDown') { if (rows.length > selectedIndex + 1) { selectedIndex++; } } else if (ele.key == 'ArrowUp') { if (selectedIndex > 0) { selectedIndex--; } } else if (ele.key == 'Enter') { selectRow(selectedIndex); } rows.forEach((row, index) => { if (index == selectedIndex) { row.classList.add("active"); } else { row.classList.remove("active"); } }); }); function selectRow(index) { searchInput.value = fruits[index]; dropdownList.classList.add("hide"); } document.addEventListener("click", (e) => { if (!searchInput.contains(e.target) && !dropdownList.contains(e.target)) { dropdownList.classList.add("hide"); } }); </script> </body> </html>Try it Yourself