Implementing jQuery Autocomplete
So I came up with this script that ajax calls google's suggestions and JSONP returns the search results. I managed to make the results sorted but I'd like to implement jquery autocomplete instead. I've tried any possible way I could think of but haven't got any results.
Here is the a working fiddle: http://jsfiddle.net/YBf5J/ and here is the script:
$(document).ready(function() {
$('#q').keyup(retrieve);
$('#q').focus();
$('#results').show('slow');
$("#q").autocomplete(parse, {
Height:100,
width:620,
noCache: false,
selectFirst: false
});
});
function retrieve() {
$.ajax({
type: "GET",
url: 'http://suggestqueries.google.com/complete/search?qu=' + encodeURIComponent($('#q').val()),
dataType: "jsonp",
jsonpCallback: 'parse'
});
}
var parse = function(data) {
var results = "";
f开发者_开发知识库or (var i = 0; i < data[1].length; i++) {
results += '<li>' + '<a href="#">' + data[1][i][0] + '</a>' + '</li>';
}
$('#results').html('' + results + '');
$('#results > li a').click(function(event) {
event.preventDefault();
$('#q').val($(this).html()).closest('form').submit();
});
}
And here's the simple body:
<body><input type="text" id="q"><div id="results"></div></body>
Any help is really appreciated. Thanks alot, rallyboy.
Here is an example of using the Jquery-UI Auto complete. Taken from your code, all i did was update the auto complete source every time the data changes using this code.
var parse = function(data) {
var results = [];
for (var i = 0; i < data[1].length; i++) {
results.push(data[1][i][0]);
}
$('#q').autocomplete({
source: results
});
See fiddle
http://jsfiddle.net/WUcpC/1/
It uses just the base CSS but that can be changed by pointing it at which ever theme you want.
精彩评论