Autocomplete for JQuery.js

Ajax Powered Autocomplete Plugin for JQuery.js

The Prototype.js version was so successfull that I had to this for JQuery, which is the library I am using the most at the moment. I have to say that the plugin works even better than the original version and in terms of coding, was easier to develop.
Its functionality is exactly the same as the mentioned one for Prototype.js:
  • Icon Notifier (Spinner between Ajax calls)
  • Fire onAjaxFailure events when an error occurs during Ajax calls
  • Be able to set a custom width
  • A more flexible and dynamic creation of the autocomplete text field
TODO

The object is pretty complete but it could be nice to include more features. Here some of them:

  • Dynamic themes. Being able to change the style of the autocomple and dropdown list could be a really nice feature to have.
  • Different effects to show/hide the dropdown list (SlideDown|SlideUp) <- This one is easy with JQuery, any volunteers?

How it works

a) Configure the HEAD section of your HTML page:

<br />
<!-- insert the styles of the autocomplete box --></p>
<link rel="stylesheet" href="css/autocomplete.css" type="text/css" media="screen" charset="utf-8" />
<!-- javascript libraries required -->
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/autocomplete.jquery.js"></script>

b) Create the objects on DOM Load (you can also create them dynamically too):

var json_options = {
script:'test.php?json=true&limit=6&',
varname:'input',
json:true,
shownoresults:true,
maxresults:16,
callback: function (obj) { $('#json_info').html('you have selected: '+obj.id + ' ' + obj.value + ' (' + obj.info + ')'); }
};
var xml_options = {
script:'test.php?limit=6&', // for the sake of the server test, json var not set
varname:'input',
json:false, // <----------- IMPORTANT
shownoresults:true,
maxresults:16,
callback: function (obj) { $('#xml_info').html('you have selected: '+obj.id + ' ' + obj.value + ' (' + obj.info + ')'); }
};
$(function(){
$('#test_json').autoComplete(json_options); // json test
$('#test_xml').autoComplete(xml_options); // xml test
});

As you can see on the code, the ‘script’ property of the object is where we write the server page to call via AJAX in order to get the dropdown results. Let’s view the important lines within this test.php page:

// here we collect the POSTED variable
// what to search?
$input = strtolower( $_GET['input'] );
$len = strlen($input);
// how many results we display?
$limit = isset($_GET['limit']) ? (int) $_GET['limit'] : 0;

Now, the way you find matches from such POSTED variable is up to you, it could be checked against an array (as in the examples included) or against a database by using the LIKE SQL statement.

Wishlist

Expose your ideas on the comments and I will list them in this small section. It seems that this dropdown keeps rocking, so why not make it better. Here goes mine:

  1. Paging Results

*note from Miroslav -thanks*

When I use only jQuery plugin autocomplete, it doesn’t work. I have to change the position of div with suggestions by using jQuery .css(“left”,pos.left) and .css(“top”, pos.top + something), otherwise it fails on div.left() and div.top() functions, which aren’t defined.

Reason

This is happening because of the problem that some browsers have with CSS properties not specified as it happens with ‘display:’ style attributes. It is not a bug from the code but from the ‘our beloved browsers’. Thank you very much Miroslav for telling us about this bug.

Updates

14-05-2010  Animations are now using easing functions, linear or swing are available when using jQuery only, more are available from http://gsgd.co.uk/sandbox/jquery/easing/ – Martin Gotik

14-05-2010 Resizing of the list (when more or less items are displayed when typing text) is now animated too, I had to remove and add some elements for it to look smooth in all browsers – Martin Gotik

14-05-2010 The list isn’t hidden anymore when doing an AJAX call when the list is visible, looks more smooth IMHO – Martin Gotik

14-05-2010 Alert in AJAX request is disabled as mentioned by Carpes on the blog – Martin Gotik

05-03-2010 Animations are more dynamic now and available for both the hide and show event – Martin Gotink.

05-03-2010 Updated the browsing through the list with the keyboard. Thanks Martin Gotink.

05-03-2010 MaxResults and MaxHeight implemented. Thanks Martin Gotink.

05-03-2010 Tested all changes with jQuery 1.4.1 and 1.4.2 on IE 6/7/8, Opera 10.10/10.50, FF 3.5 and Chrome 4.0. IE took a bit more effort (especially the maxHeight option), but the result is (almost) the same on all browsers, only IE6/7 has some small issues with the scrollbar when maxHeight is set (some strange effects when using the mouse to drag the scrollbar). Thanks Martin Gotink.

05-03-2010 Tagged all my changes with MG in the .js and .css files in the attached .zip file, so you can see what i’ve changed, and why. Thanks Martin Gotink.

21-01-2010 Fixed style positioning. Thanks Konstantin.

IMPORTANT! All changes made by others will maintain their credits from now on. Apologies for those I didn’t include as I couldn’t update this blog as much as I want due to lack of time -Far too many projects under development.

DOWNLOAD

For some reason, some of you guys cannot download (I have downloads manager plugin for wordpress and it seems that is not working properly with this resource). For those having problems to download, please download the plugin here mirror download

IMPORTANT! Demo is within the download Link -thanks Lev for pointing me this misscommunication thing.

I have updated the link so now all of you shouldnt have problems to download. Sorry for the inconvenience.

http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/img/icons/default.gif download: Ajax Powered AutoComplete for JQuery (131.75KB)
added: 17/01/2010
clicks: 5389
Tweet this!Tweet this!
  • C
    #51 written by C  1 year ago

    just to confirm, the link works after submitting a comment.

  • Mike
    #52 written by Mike  1 year ago

    Hi,

    I am using autocomplete to lookup a massive database of names ( > 400k ) by first name and last name.

    Though properly indexed, the query sometimes takes long to retrieve the results and seems to hang.

    if it takes too long …. is there a way of specifying an “abort” process?

    TIA.

  • DivDax
    #53 written by DivDax  1 year ago

    Hey!

    I’m using jQuery 1.4.2. THe Autocompleter only works with <=1.3.2
    It is possible to fix this problem so i can run this plugin with the newest jquery release?

    Thanks!

  • Antonio Ramirez
    #54 written by Antonio Ramirez  1 year ago

    I will do my best but I am busy as **** due to http://www.bookakar.com

    Best

  • Antonio Ramirez
    #55 written by Antonio Ramirez  1 year ago

    I will do my best but I am very busy at the moment due to http://www.bookakar.com

    Best

  • Martin G
    #56 written by Martin G  1 year ago


    DivDax:

    Hey!
    I’m using jQuery 1.4.2. THe Autocompleter only works with <=1.3.2
    It is possible to fix this problem so i can run this plugin with the newest jquery release?
    Thanks!

    I’m using the plugin with jQuery 1.4.1, without any problem.
    What autocomplete file did you download? Because the mirror download contains a .js file with invalid characters in the style position fix, as some ppl complain about. Maybe Antonio can fix this?

  • Antonio Ramirez
    #57 written by Antonio Ramirez  1 year ago

    Is done Martin… support for jquery 1.4.2 granted

    Regards

  • Not working
    #58 written by Not working  1 year ago

    The donwload link is not working. I can’t get the file, so I am commenting …

  • Antonio Ramirez
    #59 written by Antonio Ramirez  1 year ago

    Sorry to say… I have been hacked and I have no time to update my site… Hope I could fix it soon… Send me your email and I will forward it to you.

    Best

  • Ryan Terneir
    #60 written by Ryan Terneir  1 year ago

    Do you have example code with this? i”m looking to plug this into ASP.NET however I am quite new to JQuery so seeing an example of this would be beneficial.

    Thanks.

  • Antonio Ramirez
    #61 written by Antonio Ramirez  1 year ago

    You just need to change the PHP code on the example into an ASP.NET code that best suits your needs.

  • Ryan Terneir
    #62 written by Ryan Terneir  1 year ago

    So then pretty easy:

    var json_options = {
    script:’ReportSearch.aspx/GetCompletionList?json=true&limit=6&’,
    varname:’ctl00_contentModule_txtJQuerySearch’,
    json:true,
    shownoresults:true,
    maxresults:16,
    callback: function (obj) { $(‘#json_info’).html(‘you have selected: ‘+obj.id + ‘ ‘ + obj.value + ‘ (‘ + obj.info + ‘)’); }
    };

    Should be all i need then?

    There hsould be something I need to do to bind my textbox to that though? Or is that all?:

  • Ryan Terneir
    #63 written by Ryan Terneir  1 year ago

    I got it working for ASP.NET – works well thank you. I did some mod’s to allow more fields to be brought down etc.

    however, the big change is how you call the web service.

    the script needs to be something like:
    script:’ReportSearch.aspx/GetUserList’,

    Then, in the options for DoAjaxRequest you need:
    url: url,
    data:”{‘input’:'” + data + “‘}”,

    Where input is the parameter name. This will then hook up to the ASP.NET web service properly.

  • Paul
    #64 written by Paul  1 year ago

    Your zip file does not include the images or the test.php page you talk about. Where can i get these? Cheers

  • Antonio Ramirez
    #65 written by Antonio Ramirez  1 year ago

    Now it does have everything!

    Apologize to all of you but I had such a headache with the hacked site! Now all roles… Thanks to all!

  • Carpes
    #66 written by Carpes  1 year ago

    Hi, I have tested this Autocomplete Plugin for JQuery.js and it works very well.
    Congratulations for the code (and also to all the people collaborating with fixes and upates)! :-)
    Using JQuery 1.4.2 in PHP and with database access (MySQL). Tested in browsers IE 6 [the only browser/version showing problems: I had to disable a line in "function(status)" in autocomplete.jquery.js which shows "//alert('AJAX error: '+status);"; but it worked properly after that change], Firefox 3.6.2, Chrome 4.1.249, Safari 3.2.1, Opera 9.63, and Netscape Navigator (version 9.0.0.3).
    I downloaded the js file itself (without samples and images, posted around Mar-5-2010) and searched in Google for help. Some days till I could make all things work together, but if someone is intererested you can see a working sample here:
    http://www.genealogia.net/search.php
    (try to type schmit)
    Regards and Cheers

  • egon
    #67 written by egon  1 year ago

    where’s a demo?

  • thales
    #68 written by thales  1 year ago

    Is it works with Classic ASP and Windows server 2003 ?

  • Antonio Ramirez
    #69 written by Antonio Ramirez  1 year ago

    Hi there Thales

    Of course it does, as long as the server returned values to the client script are exactly as those provided on the example

  • thales
    #70 written by thales  1 year ago

    Can you Help me What Query can i use in ASP page

    Exp. Select customername FROM customers Where Customername Like …..?

  • Thales
    #71 written by Thales  1 year ago

    What parameter are you pass to get the results from Query?

    Exp. SELECT querypage.asp?q=Mike

    Thanks!!

  • Antonio Ramirez
    #72 written by Antonio Ramirez  1 year ago

    Hi Thales,

    If you look at the code you will find that the TEST.PHP page receives a couple of parameters:

    test.php?json=true&limit=6&

    Check test.php and you will see how this file handles the parameters JSON and LIMIT

    Regards

  • Juan
    #73 written by Juan  1 year ago

    Nice autocompleter. I come from Mootools and when I tried to use your autocompleter i had to learn what is jQuery.noConflict(); :P
    I tried to adapt it to support sending the vars via post and I get an error ‘missing ) in parenthetical’ on setSuggestions, but i don’t have much time so I’ll look for another one.
    Still a great autocompleter !!!

  • Juan
    #74 written by Juan  1 year ago

    And in case you’re wandering why post? Becasue I’m using CodeIgniter and it’s quite restrictive with the GET vars.

  • Antonio Ramirez
    #75 written by Antonio Ramirez  1 year ago

    I don’t really know why you have problems with POST and/or GET… there should be the same result whatever the technique you are using… I am now working on Yii Framework and have no problems at all… and I am using POST… you should check the Javascript code and/or the JSON response format from the server.

    Thanks for your comments anyway!

  • Metal Heart
    #76 written by Metal Heart  1 year ago

    Great plugin.

    But sometime it throw some errors.

    The first is “Object doesn’t support this property or method” in the following line in your js:
    “var results = req.getElementsByTagName(‘results’)[0].childNodes;”

    Second is “‘undefined’ is null or not an object” in this code segment:
    “if(!url || $.trim(input) == ” || $.trim(this.sInp) == ”) {
    self.clearSuggestions(); // error at this line. self element is undefined.
    return false;
    }”

    I am using ASP.NET. I’m a newbie. Can you help me with these problems? Thanks

  • Antonio Ramirez
    #77 written by Antonio Ramirez  1 year ago

    Please, could you tell me where is it happening in the code? Thanks!

  • nick
    #78 written by nick  1 year ago

    you have to comment for the dl link to work

  • Antonio Ramirez
    #79 written by Antonio Ramirez  1 year ago

    Yeah, this thingy is happening every now and then and I truly do not know why is this happening… If anybody else is experiencing the same problem, please download from the following link: http://www.ramirezcobos.com/wp-content/plugins/downloads-manager/upload/jquery.autocomplete.v5.zip

  • Antonio Ramirez
    #80 written by Antonio Ramirez  1 year ago

    missing ‘)’ ?

    Have you checked where with Firebug?

    Thanks!

  • Alex
    #81 written by Alex  1 year ago

    Hi Antonio. Can it be made to work with only one value without separators?

  • Antonio Ramirez
    #82 written by Antonio Ramirez  1 year ago

    Hi Alex,

    On the first version it was created that way, but on the latest is through the property (valueSep:’;',), set that to an impossible value (ie: valueSep: ‘;;;;;;;;;;;;;’) and thats it

  • SM
    #83 written by SM  1 year ago

    The link is not working

  • Rafael Perelló
    #84 written by Rafael Perelló  1 year ago

    Felicidades por este blog y en particular por este plugin, simplemente genial.

    Saludos.

  • Antonio Ramirez
    #85 written by Antonio Ramirez  1 year ago

    Have updated the mirror download for those who can’t without posting a comment.

  • Antonio Ramirez
    #86 written by Antonio Ramirez  1 year ago

    Gracias Rafa

  • Amit
    #87 written by Amit  11 months ago

    this is a very nice article,

    I want to apply autocomplete in gridview (in asp.net3.5 with C#) using jquery and this gridview is within the ajax update panel
    .

    For this i am using method within the

    $(document).ready(function(){
    $(‘[id$=txtItemCode]‘).autocomplete(“SearchItem.aspx”).result(function (event, data, formatted) {
    if (data) {
    alert(‘Value: ‘+ data[1]);

    }
    else {
    $(‘[id$=txtItemID]‘).val(‘-1′);
    }
    });
    });

    since in gridview the textbox id is but

    on browser such as
    and then for the next row same textbox id is now

    i tried
    1. put this code within the
    2.
    3. $(“*[@id$=theGridId] input[@id$=txtItemCode]“)
    4. jQuery.expr[':'].asp = function(elem, i, match) {
    return (elem.id && elem.id.match(match[3] + “$”));
    };
    and $(“:asp(txtItemCode)”).autocomplete…
    5.$(‘.txtItemCode’).autocomplete(“LookupCodes.aspx?type=IC”, { mustMatch: true })

    but autocomplete for textboxfield in multiple rows does not work in all the cases

    plz help me.

  • Shuja
    #88 written by Shuja  11 months ago

    Hi
    I want to use this control is asp.net. can anybody provide me working example in asp.net?

    thanks
    Shuja

  • Holger
    #89 written by Holger  11 months ago

    A little debugging help for PHP guys.

    In your backend PHP script, write to a file as you cannot echo. I.e.:

    $myFile = “testFile.txt”;
    $fh = fopen($myFile, ‘w’) or die(“can’t open file”);
    fwrite($fh, $_GET['input']);
    fclose($fh);

    Each request that REACHES your file will (re-) generate a txt file with your prints in it. No file = your file parameter is wrong, try absolute paths first.

    Good luck, hope this helps.

  • Requiem
    #90 written by Requiem  8 months ago

    Just to download the file.
    Screenshot looks awesome !

  • Herry
    #91 written by Herry  7 months ago

    Hi,

    Great work Antonio. Works like a charm. Apart from one little thing you may demystify for me.

    I made a box with citynames of the Netherlands.
    I set minChars to 2, but as soon as I hit the first 2 letters, I just get a random list of cities.
    E.g. I start typing “am” and I get “Leiden” as the first suggestion.
    As soon as I hit the third letter, everything goes fine. E.g. “ams” gives me “AMsterdam” and “AMstelveen” as well als “RotterdAM”.

    Does this have to do with some sorta setting?

    BTW The query I am using is
    $cn = $_GET['cn'];

    “select * from cities where city like ‘%$cn%’ order by city limit 0,15″;

  • Antonio Ramirez
    #92 written by Antonio Ramirez  7 months ago

    Hi Herry,

    Thanks for your comments. The issue you have is related to your query not to the plugin itself as the plugin shows the results as returned by your query. BTW, If you are using this for a project, I HIGHLY recommend you to change your query as it surely allows SQL injection attacks.

    Cheers

  • Herry
    #93 written by Herry  7 months ago

    Thanks for your reply Antonio.
    I still haven’t figured out what goes wrong. It’s only when I type the first accepted amount of letters. E.g. I tell the script to start acting as soon as I hit 3 letters. And then it gives just everything in the db-table. As soon as I hit the fourth letter, everything goes well.
    If I change the setting to start acting after the 2nd letter, it gives me all possibilties at letter 2, but it goes well at the 3rd letter.

    Another this is, how to disable the “;” that is being inserted after the selected word?

    I am aware of the possibilties of sql-injection. Just gotta read some info about how to control that.

  • Herry
    #94 written by Herry  7 months ago

    Some additional info, which hopefully may ring a bell.
    If I set cache: false, it makes it even worse.
    With cache true, I only get too many wrong results when I type the amount of chars I set in minChars (3). With cache set to false, I get all the wrong results everytime.

    PS to avoid sql-injection, I added mysql_real_escape_string() to my var.

  • Herry
    #95 written by Herry  7 months ago

    OK, I solved my issue by downloading from the direct link, instead of the mirror. Apparently there’s some differences.

    I am still struggling with the valueSep tho. Setting it to an impossible value, as mentioned above, doesn’t help.
    But furthermore I am really happy! Thanks a lot!

  • Herry
    #96 written by Herry  5 months ago

    Still running into issues…
    mostly an error which says:
    AJAX error: [object XMLHttpRequest]

    E.g. I have the script running perfectly well. I look up some information, and submit my form. while displaying the results the search form is placed on the page again (exactly the same functions being called), but now when I type in a few letters in the search box, it gives me the above mention error.
    Any idea?

  • Antonio Ramirez
    #97 written by Antonio Ramirez  5 months ago

    That is a very general error, very difficult for me to help you out, try this:


    $.ajax({
    /* ajax options omitted */
    error: function (xmlHttpRequest, textStatus, errorThrown) {
    if(xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0)
    return; // it's not really an error
    else
    // Do normal error handling
    });

  • Matthias
    #98 written by Matthias  2 months ago

    Hey! This is a nice script and almost the thing I was looking for. I downloaded “Autocomplete Plugin for JQuery 1.3.2″ and played around with it. Can I somehow configure that I only want to search one entry and not more, so no separation would be needed. I’d also like to disable the autocompletion after an entry has been found and checked (clicked or chosen by the arrow keys and confirmed with return key). So I can add additional infos without trying to get another lookup. What I want to do: provide a list of street names for and add a house number. I appreciate your help!

    Thanks and cheers
    Matthias

  • tim
    #99 written by tim  1 month ago

    hi,

    unlike Herry, do i think its neat to have a autoSuggest that shows
    several combinations not necessarily Starting with the correct phrase.

    Meaning: a search on a variable: AM should show a dropdown like
    Amsterdam, but also flAMe and Prince WilliAM etc…

    also, at the same time i don’t want no “no results” message returned at any time.

    how to achieve this?

  • tim
    #100 written by tim  1 month ago

    ps. the “no results” is in the autocomplete.jquery.js so skip that.

    as for the search returns i am using the xml version
    and the database does return records all holding the “AM” variable
    anywhere in the field.

    I am using LIKE ‘%$var%’ in the query so it should be in the script i presume…

  • You may use these HTML tags: <a> <abbr> <acronym> <b> <blockquote> <cite> <code> <del> <em> <i> <q> <strike> <strong>

  • Comment Feed for this Post
Go to Top