user1729898
user1729898

Reputation: 81

jQuery autocomplete "response" event

I'm using jQuery UI autocomplete as described [http://api.jqueryui.com/autocomplete/]

I need to do a few things before and after the search is executed. From reading the documentation at the above URL it describes two methods "search" and "response," that are triggered before and after the query is run - perfect. BUT, if I add these to my code, "search" works perfectly, but "response" is never called. What am I doing wrong? All my code works, no javascript errors, autocomplete works perfectly. But I just dont ever have the "response" method being triggered.

$(function() {
             $("#tv").autocomplete({
                source: "a_url_providing_json",
                minLength: 4,
                select: function(event, ui) {
                    $('#state_id').val(ui.item.id);
                    $('#abbrev').val(ui.item.abbrev);
                },
                search : function(a,b) {
                     alert('this works!');
                },
                response : function(a,b) {
                     alert('this doesnt!');
                } 
        })    
    }); 

Many thanks for any advice !

Upvotes: 8

Views: 16313

Answers (2)

Rick Hanlon II
Rick Hanlon II

Reputation: 21667

Assuming that all of your code is correct, you may need to upgrade your version of jQuery UI (and the corresponding jQuery as well). This is because although the documentation you were looking at says "Autocomplete widget version added: 1.8," the response event was not added until 1.9 (See the jQuery 1.9 Upgrade Guide: Response Event) This also means that you will not be able to "Bind an event listener to the autocompleteresponse event" as the guide states.

Once you upgrade to a jQuery and jQuery UI version which supports the autocomplete response event, this code will work as expected.

As a tip to anyone new to this event, keep in mind that if you modify the data, you need to include both the value and label properties for each item you want to add, even if your source data was just an array of values. This is because once the content gets into this event, it has already been 'normalized' (that is, the label has been pared with a value).

So if you want to add "Other" to the results returned, your response event would look like:

response: function (e, ui) {
  ui.content.push(
    {label:"Other", value:"Option"}
  );
}

This will add an "Other" option to every list, which will have a input value of "Option."

Upvotes: 2

Johan Nordin
Johan Nordin

Reputation: 161

This callback-method arrived with the new jquery-ui. I could not get this to work, but after i updated from 1.8.20 to 1.9.2 the callback fires just as it is supposed to.

Hope it helps!

Upvotes: 10

Related Questions