Autocomplete with categories and a remote data source

What I want to do is to classify the results using autocomplete through the jQueryUI function. After some googling etc. I found that it has a built-in function (http://jqueryui.com/demos/autocomplete/#categories), but this example is only for a local data source (array in javascript). I am dealing with a remote data source. The autocomplete side works fine without adding a category code, but breaks when it is added.

This means that the PHP code is ok (a search page that returns json data).

I took this code from jQueryUI site:

$.widget( "custom.catcomplete", $.ui.autocomplete, { _renderMenu: function( ul, items ) { var self = this, currentCategory = ""; $.each( items, function( index, item ) { if ( item.category != currentCategory ) { ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" ); currentCategory = item.category; } self._renderItem( ul, item ); }); 

Then I combined it with the search side (changing the category):

 $(function() { $( "#search" ).catcomplete({ delay:0, source: "query/encode-json.php?term="+ $("#search").val(), select: function(event, ui){ alert(ui.item.label); } }); }); 

But this does not work :( I searched a lot, but everyone else had problems on the part of json. Here is my json data:

 [{"value":"some dude","id":"1","category":"artist"},{"value":"some other dude","id":"2","category":"artist"}] 
+4
source share
3 answers

I am sure that your problem is the source property of the options object that you pass to autocomplete:

 $("#search").catcomplete({ delay:0, source: "query/encode-json.php?term="+ $("#search").val(), select: function(event, ui){ alert(ui.item.label); } }); 

source will be evaluated once when creating the widget instance. In other words, $("#search").val() does not run every time a user types.

Since autocomplete sends term to the query string by default, you should just do:

 $("#search").catcomplete({ delay:0, source: "query/encode-json.php", select: function(event, ui){ alert(ui.item.label); } }); 

I'm sure everything else is true, since using your array as a local data source with categories works great: http://jsfiddle.net/jadPP/

+2
source

The _renderItem() method by default looks for item.label , but your json data contains item.value . You need to modify your encode-json.PHP script to use label instead of value , or you will have to use the source: version, where you provide your own callback function.

0
source

All Articles