How to use autocomplete (suggestion) in bootstrap?
April 29, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
Today, I am going to show you. How to use autocomplete (suggestion) in bootstrap with code example.
Here, we will use the .typeahead
class to make use of autocomplete in bootstrap.
In this article, we will learn to implement dynamic autocomplete search using Bootstrap Typeahead. Bootstrap Typeahead
is a plugin that helps to add a beautiful autocomplete option in the search bar.
In this approach, we will be taking static data for autocomplete, but we can also use dynamic JSON data as well, to show search options.
Example.
Let’s look at the following example to understand how it basically works:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js">
</script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />
<style>
body {
background: #3F51B5;
}
.page-title {
color: #ffffff;
font-weight: 800;
}
.typeahead {
width: 50%;
}
.autocomplete {
position: relative;
display: inline-block;
}
.autocomplete-items {
position: absolute;
z-index: 99;
top: 100%;
left: 0;
right: 0;
}
</style>
</head>
<body style="text-align: center">
<div>
<p class="page-title">Suggest the states of India</p>
<input type="text" class="typeahead" data-provide="typeahead" placeholder="Enter name of states of India " />
</div>
<script>
// Initializes input( name of states)
// with a typeahead
var $input = $(".typeahead");
$input.typeahead({
source: [
"Andhra Pradesh",
"Arunachal Pradesh",
"Assam",
"Bihar",
"Chhattisgarh",
"Goa",
"Gujarat",
"Haryana",
"Himachal Pradesh",
"Jharkhand",
"Karnataka",
"Kerala",
"Madhya Pradesh",
"Maharashtra",
"Manipur",
"Meghalaya",
"Mizoram",
"Nagaland",
"Odisha",
"Punjab",
"Rajasthan",
"Sikkim",
"Tamil Nadu",
"Telangana",
"Tripura",
"Uttar Pradesh",
"Uttarakhand",
"West Bengal",
],
autoSelect: true,
});
$input.change(function() {
var current = $input.typeahead("getActive");
matches = [];
if (current) {
// Some item from your input matches
// with entered data
if (current.name == $input.val()) {
matches.push(current.name);
}
}
});
</script>
</body>
</html>
In the above code, we have used .typeahead
class to autocomplete in bootstrap
Check the output of the above code example.
All the best 👍