如何使用Bootstrap Typeahead创建动态自动完成搜索
在这篇文章中,我们将学习如何使用Bootstrap Typeahead实现动态自动完成搜索。Bootstrap Typeahead是一个插件,有助于在搜索栏中添加一个漂亮的自动完成选项。
在这种方法中,我们将采取静态数据进行自动完成,但我们也可以使用动态JSON数据,以显示搜索选项。Typeahead插件中使用的方法如下。
- .typeahead(options)。用一个typeahead初始化一个输入。
- .lookup。要从外部触发查找功能。
- .getActive。要获得当前的活动项目,你将得到一个字符串或一个JSON对象,这取决于你如何初始化typeahead。它只对第一次匹配起作用。
例子: 下面的例子演示了使用Bootstrap Typehead的动态自动完成搜索。
<!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>
.typeahead {
width: 50%;
top: 60px !important;
left: 50px !important;
}
</style>
</head>
<body style="text-align: center">
<div>
<b><p>Suggest the states of India</p></b>
<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>
输出 :
动态自动打字机