I’m using http://jsfiddle.net/dhoerster/BXYpt/ from jQuery UI autocomplete with values as the basis. This does exactly what I need it to except that I need to be able to have OR conditions. I’ve created a fiddle as a demo:
My issue is this: the demo items are Car, Phone, and Car With Phone. Is there a way to make autocomplete handle three cases: the string contains case (the default) followed by an ANDed case and lastly by an OR case? So if I enter “Car Phone” it would result in:
1) first case – 0 results as “Car Phone” isn’t a substring of any of the labels.
2) second case – 1 result because “Car” and “Phone” appear in “Car With Phone”. This gets added to the list below the 0 results preceding.
3) third case – 2 more results are displayed because the labels “Car” and “Phone” contain at least one of the search items. These results appear below the previous results of stages 1 and 2 so the selection box below should now render:
Car With Phone
Car
Phone (Car and Phone order really don’t matter as they’re both equally right)
Here is the javascript in question:
$(document).ready(function() {
$( "#topics" ).autocomplete({
minLength: 1,
source: topics,
focus: function( event, ui ) {
$( "#topics" ).val( ui.item.label );
return false;
},
select: function( event, ui ) {
$( "#topics" ).val( ui.item.label );
$("#topicID").val(ui.item.id);
$( "#results").text($("#topicID").val());
return false;
}
})
});
So would it be possible to have it do in order:
1) string.contains (default)
2) string split –> AND condition
3) string split –> OR condition (no preference to sorting by the number of terms contained)
What we’ll have to do is do our own search on the data for the “AND” and “OR” results. My first thought was to do this using the
responseevent of the autoselect, and add the results to the ones gathered by the library itself. However, when writing it, I realized that I had to do the normal search anyway in order to prevent results showing up twice. Instead, I’ll be specifying a function for thesourceproperty and do all the sorting myself.(Using the earlier method, I also ran into a jquery-ui bug (with the new messages showing how many results were found) which does not come up with the newer approach.)
Well, it’s pretty straight forward from here, so let me just show the code:
A little explanation: we don’t give our topics to the library anymore as the source, but instead we’re keeping the source for ourselves as we search through it ourselves. We do this using three arrays, each one of which will contain one of the three types of results, so we can keep the order correct. Finally, we merge the three arrays after we’re done populating them.