How can I include suggestions like from Google suggest in my own auto complete box
The following code sh开发者_StackOverflowows an auto complete function which only uses the data which I have given. I want to be able to change the data source so that when using the auto complete, common Google searches will be displayed. How could I do this?
<html>
<head>
<script type="text/javascript"
src="http://www.google.com/jsapi?key=ABQIAAAARh4zAaoctlNef6M1fBHLSRT_pkQkDorgHY-QpTBEqS9oVy079BTA6a35AAdpXz6ExAMdICz8lNWRVA"></script>
<script>
google.load("jquery", "1.4.2");
google.load("jqueryui", "1.8.2");
</script>
</head>
<body>
<script>
$(document).ready(function () {
var myData = ["One", "Two", "Three"];
$("#myTestField").autocomplete({
source: myData
});
});
</script>
<form>
<input type="text" id="myTestField" />
</form>
</body>
</html>
As you can see in the sample code possibilities are defined in the myData array. You need to set up a php (or any other technology) serverside script to return data based on a starting string. That data will be polled through AJAX and used by the autocomplete.
I didn't find the sample code that intuitive to do this myself so I'll put something basic here for an autocomplete search box using ASP.NET MVC.
jquery:
<script>
$(function () {
$("#search").autocomplete({
source: '/Search'
});
});
</script>
ASP.NET MVC:
public ActionResult Search(string term)
{
List<string> results = new List<string>();
foreach (var x in y) // where y is what you are searching
{
if (x.Contains(term))
results.Add(x);
}
return Json(results);
}
精彩评论