jQuery plugin: Autocomplete

Autocomplete an input field to enable users quickly finding and selecting some value, leveraging searching and filtering.

By giving an autocompleted field focus or entering something into it, the plugin starts searching for matching entries and displays a list of values to choose from. By entering more characters, the user can filter down the list to better matches.

This can be used to enter previous selected values, eg. for tags, to complete an address, eg. enter a city name and get the zip code, or maybe enter email addresses from an addressbook.

Current version: 1.1
Compressed filesize: 8.001 bytes
License: MIT/GPL
Tested in: Firefox 3, IE 6 & 7, Opera 9, Safari 3

Files:

Download
Changelog
Demos
Documentation (Plugin Options)

Dependencies

Required

Optional

  • optional: bgiframe plugin to fix select-problems in IE, just include to apply to autocomplete

Support

  • Please post questions to the jQuery discussion list, putting (autocomplete) into the subject of your post, making it easier to spot it and respond quickly. Keep your question short and succinct and provide code when possible; a testpage makes it much more likely that you get an useful answer in no time.
  • Please post bug reports and other contributions (enhancements, features) to the plugins.jQuery.com bug tracker (requires login/registration)

Donate

$ USDDonate€ EURDonate

341 Responses to “jQuery plugin: Autocomplete”

  1. andreas says:

    Small bug: The even list items are in class ac_even*t* instead of ac_even.

    Thanks for all your work
    Andreas

  2. Remy Tiitre says:

    Would it be a bad idea to add a new trigger thats executed when the text is not in the options list. I mean, if you enter something thats not listed. mustMatch doesnt seem to work, and I would like to run some code anyway when that happens. I don’t think its possible right now.

  3. Remy Tiitre says:

    ac_loading is not working. In FF at least the class gets never assigned to input box. I added sleep(10) to my php script to test that and no results. Tried to use loadingClass as well, but it seems to have the same problem. Might be that I do something wrong.

  4. Remy Tiitre says:

    Why I can’t use
    $('#user_name').result(function(event, data, formatted) {}).focus();
    when I use keyboard? Something is takeing the focus away. If I use mouse, everything is working ok.

  5. Joe Dolan says:

    This is a great script! Could you add to the notes that if you do not want a max parameter, enter the ‘max’ parameter as 0 (max: 0). I was able to solve it by trial and error, but I figure it will save others that are looking to do the same thing a little time.

    Thanks,

    –Joe

  6. Raman Basu says:

    I made some changes in your autosuggest so that it shows preformatted html like images in the list, thus making it Image-List control. I have done it using asp.net.

    Have a look please.

    http://ramanbasu.com/tricks/autosuggest/default.aspx

  7. Corey Coto says:

    Jörn,

    Great plugin!

    I made a minor modification to the plugin that allows JSON data to be loaded from a URL. If you are interested in checking out my change and merging it into your code please let me know. I think it would a great enhancement because it allows you to load data from web services.

    Thanks,
    Corey

  8. The ac_odd and ac_event styles are removed when you change the ac_over from one item to another.


    function moveSelect(step) {
    // specify which class is to be removed: CLASSES.ACTIVE
    listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);

  9. Jiming says:

    Jörn,

    Thanks for this great plugin!

    As a autocomplete, i think it is powerful enough so far. I want to use it as a SELECT like plugins in certain case, and I do not want to add another plugin since I like this one very much. But using this one, my select options will be filtered when user input chars, which does not behave as a SELECT do, could you please consider of adding an option to forbidden the filter feature?

    Thanks again!

    Jiming

  10. dineshv says:

    I know this question has been asked but I haven’t seen a complete response yet.

    - Has JSON support been fixed (as per Jorn’s email of July 4, ‘07)?

    - How do you use the AC plugin for remote data which is requested again and again?

    - Is there example code someplace?

    Cheers

    Dinesh

  11. Raman Basu says:

    How about creating dynamic client side multiple row addition feature with autosuggest? :)

  12. xyz says:

    In opera, when You are choosen (by UP or DOWN key) an item, the cursor moves in main textarea. When I press Enter, then the item is insert in textarea exactly where is cursor (wchich was moved) and is problem. Is any way to stop moving cursor in textarea during choosing item from list?

  13. Sean says:

    Hello

    I would like to pass a value of the current and also a different field into the external script so that it returns relevant results to the autocompleter.

    Is something like this possible?
    input#county is the current field – for auto completion

    $.getJSON(base_url+"search/jquerycountysearch/"+$("input#county").val(), function(data){
    $("input#county").autocomplete(data, {
    minChars: 0,
    width: 310,
    matchContains: true,
    formatItem: function(row, i, max) {
    return row.optionValue + " <" + row.optionValue + ">";
    },
    formatResult: function(row) {
    return row.optionValue;
    }
    });
    })

    Thank you
    Sean

  14. Hi folks!
    First of all: Jörn, thank you for the great plugin!

    I have a question that maybe is related in my lack of knowledge in javascript programming but I think that it could help someone else in my same situation :)

    I have initialized some autocomplete fields successfully, i have setup an onload event which changes extraParams trought setOptions() basing on some server-side conditions, now I need to dinamically change one (and only one) extraParams. Is there a way for “accessing” the options object for every autocomplete?

    I’ve tried adding a getOptions() function right after setOptions() in the sourcecode but without success, I cannot understand why it doesnt work:

    /*...*/
    setOptions: function(options){
    return this.trigger("setOptions", [options]);
    },
    getOptions: function(){
    return options;
    }
    /*...*/

    Forgive my bad language and my stupid question.

    Thanks in advance.

    Alex

  15. solot says:

    hi, is this usable for an input filed like gmails address bar, where you can enter N values separated by comma.

  16. Andrea says:

    if i type a letter, then remove it from the input box using del key, then type again the same letter the options list doesn’t appear anymore!
    it does if i type a different letter the second time or if i remove it the first time using backspace.
    is it a bug?

    Thanks

  17. Chintan says:

    I have just begun using this feature. I want to implement the autocomplete feature which requires me passing extra parameters. I am not able to do it using the extraParams option. Even I am not able to add any options. Firebug replies with the error

    ‘Syntax error’ on the line where I bind the autocomplete feature to the input textbox


    $("#DATA_POINT_TEXTBOX34").autocomplete("/main/control_ui_editor.php",{delay:10});

  18. andrew l says:

    thinkI found a bug and the solution. when you use the arrow keys to move up and down a result list all classes are removed from the selected item upon selection change. The problem with this is that you loose your odd row styling.

    The problem is in
    function moveSelect(step) {
    istItems.slice(active, active + 1).removeClass();
    ……

    the removeClass call should be limited to the over class like so

    listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);

    hope that makes sense and is helpful for someone.

  19. jiangti says:

    Is there a way that i can search from the middle of a word?

    For example, the word i type in is “manipu” and the result bring up “image manipulation”

  20. brad vincent says:

    Hey Jörn
    thnx for the excellent plugin.
    i noticed some issues
    1) when you move down the list with arrow keys the alt row styling is lost
    2) when you get the end of the list it goes to the begining and when u go up from the 1st item it goes to the end.

    i edited the following functions to overcome the above :

    function movePosition(step) {
    active += step;
    if (active = listItems.size()) {
    active = listItems.size() – 1;
    }
    }

    function moveSelect(step) {
    //old :listItems.slice(active, active + 1).removeClass();
    listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
    movePosition(step);
    var activeItem = listItems.slice(active, active + 1);
    activeItem.addClass(CLASSES.ACTIVE);
    if(options.scroll) {
    var offset = 0;
    listItems.slice(0, active).each(function() {
    offset += this.offsetHeight;
    });
    if((offset + activeItem[0].offsetHeight – list.scrollTop()) > list[0].clientHeight) {
    list.scrollTop(list.scrollTop()+ (offset + activeItem[0].offsetHeight – list.scrollTop()) – list[0].clientHeight);
    //old : list.scrollTop(offset + activeItem[0].offsetHeight + list[0].clientHeight);
    } else if(offset

  21. Dayberry says:

    I have been unable to add an onchange event for any field with an autocomplete. Is there any way to achieve this?

  22. nicolas says:

    For the focus, I have just add the followings parameters, and it works fine in FF:

    multiple: true,
    multipleSeparator: “”

  23. Prem says:

    Hi, Do I need to purchase any license to uses your code in my project

    Prem.

  24. John says:

    Awesome work – but I’ve been wondering how to do the following:
    My php script (for a remote lookup) can accept a variable ’s’ which changes it’s behaviour from matching anywhere in the data, to matching from the start of the data.
    I would like to have a checkbox to enable/disable this.
    I know I need to add (and remove) extraParams{s:1}, but I don’t know how to add this dynamically to the autocomplete(…) settings?
    Any help welcomed!

  25. thiago says:

    finnally, how can we use autocomplete with data comming from server as a JSON string to be parsed at client side?

  26. Hesham says:

    3 things:

    1) First of all, great work! This is absolutely marvelous. :-) )

    2) I had trouble with select elements poking through the list when I scrolled using mouse wheel or keyboard. It turns out that my html doctype declaration had the word. Transitional. As soon as i removed “Transitional” the problem cleared.

    was:

    changed to:

    The side effect of my changing the doctype was that my elements were misaligned; I therefore fixed that via CSS :

    body, td, th, textarea {
    font-family: Arial, Helvetica, sans-serif, Geneva, “Bitstream Vera Sans”,”Trebuchet MS” ;
    font-size: 12px;
    text-align:left;
    }

    3) when i select an item from the list using the enter on keyboard, the focus is entirely lost from the element. I read something quickly on this forum, but am not sure how to address it.. i will propbably need to look deeper into the options or add code to put back the focus to the element. If you happen to stumble on this, please drop me a quick email and let me know the most elegant way to address this.

    Best regards and thank you for sharing your great work, all of you,

    Hesham

  27. Hesham says:

    Question: is there any way to work around the elments poking through the list without having to change DOCTYPE ? That would really save me a lot of hassle having to heavily customize my css.

    Any help you can provide is greatly appreciated. :)

    I’m running the autocomplete on IE6.

    cuasing the problem: DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”

    Removing the word Transitional clears the problem.
    sorry for repeating this, I tried pasting the code without success.

  28. dineshv says:

    I know this is a simple question but … In the Autocomplete multiple
    cities example (http://dev.jquery.com/view/trunk/plugins/
    autocomplete/) how do you send the final set of chosen entries to the
    server ie. all the values in the input box when “Get Value” is
    clicked?

    Cheers

  29. Wim Leers says:

    I can confirm Fabien Meghazi’s comment of January 28: focusing before setting up autocomplete leads to a very malfunctioning autocomplete.

    $("#autocomplete).focus().autocomplete("suggestions.php");

    At least in Firefox 2 and Safari 3 this is not working. It’d be cool to either mention this in the FAQ or to fix this.

    Thanks for this awesome plugin!

  30. rino sassi says:

    Jörn, thanks a lot for your work.
    my problem *was*:
    a user write some letters of a name in an input box; ajax goes into a database, pick the matching surnames, emails, phones…, and list them as:
    name surname – email
    the user picks one row from the list and then the input boxes such as surname, email, phone are filled with the corresponding data.

    i was going mad.
    with your scripts i’ve done it in minutes.
    thanks, again.

  31. Raja says:

    Hi,

    Is there any method which can be called to find out if the autocomplete AJAX query is still executing and the autocomplete options are still to be displayed?

    Thanks and Regards,
    Raja.

  32. Dayberry says:

    I have a small problem with your code. I am using a combination of multi selects and single. On the multi select, when you select an item or two and hit tab, it goes to the next text box, on the single, the cursor disappears and if you hit it one more time, it goes to the very first text box on the page. It would be very handy if hitting tab again simply continued through the form fields.

  33. theintoy says:

    Jörn and other gifted peeps

    Hi.

    I am trying to do something that seems obvious to me, yet a little weird as nobody else seems to have asked or done it.

    I have the plugin working fine, and the backend script supply all the correct data. As the lookup successfully finds what it is looking for, I am trying to make the information returned in the list http link to the found row:
    e.g.

    function formatItem(row) {
    return "" + row[1] + "";
    }

    function formatResult(row) {
    return row[1];
    }

    $('#ajaxsearch').autocomplete("search.php", {
    width: 800,
    max: 20,
    formatItem: formatItem,
    formatResult: formatResult
    });

    The information replied from the server is:
    http://www.example.com/first_link.htm|First link…

    The problem iis, when the user clicks the link in the list the click is consumed by the component and the href link is not followed.

    How can I get this component to not consume the click and therefore enable the browser to follow the href link?

  34. theintoy says:

    OOOppppssss, sorry forgot to format one of the above functions correctly:


    function formatItem(row) {
    return "&lta href='" + row[0] + "'&gt" + row[1] + "&lt/a&gt";
    }

  35. dineshv says:

    I’ve noticed that if multiple: true and multipleSeparator: ’string’ that it always defaults to string=”, “.

  36. Tuyra POL says:

    Hi;
    I want to use multiple suggest with one file.
    For ex:

    $().ready(function() {
    $("#tyur").autocomplete("hehe.php", {
    width: 260,
    selectFirst: true
    });
    });
    $().ready(function() {
    $("#sdsd").autocomplete("hehe.php", {
    width: 260,
    selectFirst: true
    });
    });

    in hehe.php
    if ($_GET['q'])
    ??????? how can i use it ?

  37. Is there a method for setting a post-selection call back? I’ve tried using formatResult, but that is being called during the data acquisition. I’m looking for a way to append data resulting from the selection to a hidden input field.

  38. Chris says:

    Hey theintoy,

    I was just on here and thought I *might* be able to help.

    Here’s something I use:

    $("#driverName").autocomplete("../ajax/DriverSearch.php", {
    delay: 150, minChars: 3, width: 336, max: 10, matchSubset: false, scroll: false,
    formatItem: function (row){
    return "" + row[0] + "" +
    "" + row[2] + "";},
    formatResult: function (row){return row[0] + "...transferring...";}
    });
    $("#driverName").result(function(event, data, formatted) {
    $("#driverName").attr("disabled", "disabled");
    document.location.href = 'DriverDisplay.php?driverID=' + data[1];
    });

    I’m no expert but I think it does what you’re trying to accomplish.

  39. Jörn says:

    @Jean: You can now use the formatMatch-option to specify what to use for searching.

    @al_shopov: Thanks, fixed.

    @graeme d: Wrap the value in a function which returns it, it’ll get called before sending the request.

    @Piotr Gabryjeluk: Thanks for the pointer, fixed in latest revision.

    @al_shopov: Tickets are preferred for specific requests.

    @Gideon: Fixed in 1.0 release.

    @Markus: Currently not supported.

    @Allan Kikkas: Fixed in 1.0 release.

    @mansoft: I’ve successfully used the plugin with german umlauts, yes. Its mostly a matter of the server sending the right encoding – where UTF-8 yields the most reliable results.

    @xyz: That fix is now part of the 1.0 release.

    @Engels: That issue is fixed in the 1.0 release. Now only the ACTIVE class gets removed on scrolling.

    @andreas: Thanks, fixed!

  40. Jörn says:

    @Joe Dolan: I’ll give that a try and add it to the docs. Thanks.

    @Brian: Thats fixed in 1.0.

    @Jiming: So you want just the list, without any filtering? Whats the point of a replacing a select then?

    @dineshv: Setting up json-powered autocomplete is possible and there are several json-examples in the demo. More to come.

    @Sean: You should pass that county-data as a parameter, using the extraParams-options. It accepts a callback as parameters, so you just have to specify a function that returns the current county-value.

    @Alex: Same as above, use extraParams with functions as the value.

    @solot: Yes, it is, with the limitation that values can be added only at the end of the input. Take a look at the multiple-option and related examples in the demo.

    @Andrea: Yes, that is a bug. Thanks for reporting, I’ll take a look.

    @jiangti: Yes, via the matchContains-option.

    @brad vincent: The first issue is fixed. The second is intended behaviour, allowing you to navigate to the end of the list very fast, or back up to the top.

    @Dayberry: I’m working on a solution to improve tab-handling.

    @Prem: The code is dual-licensed under MIT and GPL, like jQuery itself. Donations (via Paypal) are welcome.

    @John: Use the setOptions method.

    @Hesham: The focus/blur issue has top priority. Its in place to avoid the even more annoying issue of accidentally submitting the form.

    @Wim Leers: Thanks for confirming the issue and providing example code. I’ll try to fix the issue.

    @Raja: You could leverage jQuery’s global ajax events to track requests. They all provide the settings that are passed to $.ajax as an argument, so you could match autocomplete requests via settings.url.

    @theintoy: Thats an interesting problem of unintended usage. I’ll have to give it a try to see how a workaround could look like. A testpage would help.

    @Tuyra POL: What exacetly is the issue?

    @Rogers Hellman: Yes, using the result(Function )-method.

  41. Jörn says:

    Comments are now closed.

    • Please post questions to the jQuery discussion list, putting [autocomplete] into the subject of your post, making it easier to spot it and respond quickly.
    • Please post bug reports and other contributions (enhancements, features) to the jQuery bug tracker (requires registration). Please put [autocomplete] into the title of a ticket.