This page shows how to create a autocompletion box with the dropdown component of Bootstrap.
This is an adaptation of the autocompletion box code to the Bootstrap styling.
You need to know the basic of an autocompletion box.
If you don't know how it works under the hood, read this article: How to create an Autocompletion functionality with CSS, Javascript and HTML
The container of dropdown box on Bootstrap 1) is a div box with:
<div class="dropdown">
<input
type="text"
class="form-control"
id="color-input"
placeholder="Type of color"
autocomplete="off"
>
<ul class="dropdown-menu"><!-- Build dynamically --></ul>
</div>
We just reuse the function that creates the autocompletion list of the original article.
The adaptation are:
The code:
let colors = ["Blue","Red","Yellow"];
function rebuildAutoCompletionList(searchTerm, listElement, inputBox){
console.log(`filtering value ${searchTerm}`);
/* Reset the content */
listElement.innerHTML="";
/* No search term */
if(searchTerm==""){
return;
}
/* Filtering of the data */
let pattern = new RegExp(`.*${searchTerm}.*`,"i");
let selectedColors = colors.filter(e=>pattern.test(e));
if (selectedColors.length==0){
return;
}
/* Creation of the bootstrap autocompletion list item */
for(color of selectedColors){
let li = document.createElement("li");
/* To be able to determine that an item was clicked */
li.classList.add("dropdown-item");
/* We make li focusable to get on the relatedTarget it when we click */
li.setAttribute("tabindex","0");
li.innerText = color;
/* When the element is clicked, set the value of the search Box */
li.addEventListener("click", function(){;
if (inputBox != undefined){
/* Set the value in the input box */
inputBox.value = this.innerText;
/* Remove the list */
listElement.classList.remove("show");
} else {
console.log(`No input box defined, the selected value was ${this.innerText}`);
}
});
listElement.append(li);
}
}
The elements used in javascript later
let inputBox = document.getElementById("color-input");
let completionListRoot = document.querySelector("#color-input ~ .dropdown-menu");
inputBox.addEventListener("focus", function(){
/* on focus, create the list */
rebuildAutoCompletionList(".*",completionListRoot,this);
completionListRoot.classList.add("show");
/* on blur, delete it */
inputBox.addEventListener("blur", function(event){
/* blur can also happen when we click on a list item, we don't remove the list in this case */
if (event.relatedTarget == null ||
(event.relatedTarget !=null && !event.relatedTarget.classList.contains("dropdown-item"))){
completionListRoot.classList.remove("show");
}
});
});
On change we rebuilt the list
inputBox.addEventListener("input", function(){
let searchTerm = this.value;
if (this.value==""){
searchTerm = ".*";
}
rebuildAutoCompletionList(searchTerm,completionListRoot,this);
});
The result is: