What I want to do is have categorised results using autocomplete through jQueryUI’s function. After some googling etc I found that it has an inbuilt function (http://jqueryui.com/demos/autocomplete/#categories) but the example is only for a local data source (an array in javascript). I am dealing with a remote data source. The autocomplete side of it works fine without the categories code added in but breaks when it is added.
This means that the php code is fine (the search page that returns json data).
I took this code from the 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 );
});
I then combined it with the search side of it (changing to category):
$(function() {
$( "#search" ).catcomplete({
delay:0,
source: "query/encode-json.php?term="+ $("#search").val(),
select: function(event, ui){
alert(ui.item.label);
}
});
});
But it does not work 🙁 I’ve googled a lot but everyone else was having issues with the json side of it. Here’s my json data:
[{"value":"some dude","id":"1","category":"artist"},{"value":"some other dude","id":"2","category":"artist"}]
I’m pretty sure your problem is the
sourceproperty of the options object you’re passing to autocomplete:sourcewill be evaluated once when you instantiate the widget. In other words,$("#search").val()does not get executed every time the user types.Since by default autocomplete sends up
termin the query string, you should just be able to do:I’m pretty sure everything else is correct, since using your array as a local data source with categories works fine: http://jsfiddle.net/jadPP/