4

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 = "";
    for (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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Very nice sir. Very appreciated. I found a minor problem. It seems that if you type the first letter and get the results, when you clear all your caption and start typing again, it only gives you results of the first letter you've typed. It something like it doesn't returns back
Actually sorry. If you type a letter and select something from the autocomplete, it parse's results of that selected item only. So for example if you type 's'and select skype, if you delete your caption and type 'a' it gives you results about skype. Thanks alot
I am unable reproduce what you are saying if i type 's' select Skype and then type a i get amazon and other words starting with a. Maybe type no cache option in the auto complete. Whats your browser?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.