luchomolina luchomolina - 4 months ago 6x
Javascript Question

jQuery UI Autocomplete Widget: modifying response data in "response" event doesn't have any effect

From the JQuery UI docs:

event is) triggered after a search completes, before the menu is shown. Useful for local manipulation of suggestion data.


argument) contains the response data and can be modified to change the results that will be shown.

Hoewever, if I modify
on the
event it doesn't affect the results shown in the dropdown, instead my code is just ignored. Here's my (test) code:

source: new Array({label: 'test1', value: 'test1'}, {label: 'test2', value: 'test2'}),
response: function( event, ui ) {
ui = {content: new Array({label: 'test3', value: 'test3'}, {label: 'test4', value: 'test4'})};

In theory, if the term is "t", it should display test3 and test4 as my autocomplete options, but it doesn't. I get test1 and test2.

What am I missing?

I'm using version 1.9.2 in case you want to point me to this thread.


What if you try to set the source for your search using source attribute, instead of intercepting the response? Look at this fiddle.

It basically does it this way:

        source: [

P.S. It comes from this question: Detecting no results on jQuery UI autocomplete

Edit 1: Well. If you set a console.log at some point in the response event (like in this example), it will tell you that ui.content has two elements, even if the search returns no results. So, it looks like the problem is sending the updated ui in the callback. Still looking...

Edit 2: Got it in a way. Look at this updated jsfiddle. It clears the content array and sets the new one. Still guessing why it does not get empty after something like ui.content = []; and it kinda annoys me. Maybe it's related to the fact it is inside a JQuery object (even if it's defined as an pure and simple Array.

The fiddle

I just use push method to put the desired key-value combinations in the array.

// Set default content
      for ( var i = 0; i = ui.content.length; i++ ) {
      ui.content.push({ label: "pepe", value: "pepe" });

And it works, as it always shows the desired list of suggestions. Hope it helps and perhaps someone else finds a more elegant solution.

Edit3: Just to add the solution that @andrewWhithaker suggests, as it works as well (haven't checked if it takes longer in case the original content array is too big).

The fiddle with splice

It changes the whole pop and push on the previous approach with one splice.

 ui.content.splice(0, ui.content.length, { 'label': 'test3', 'value': 'test3' });