JQueryUI Autocomplete with Opensearch Suggestions

The Opensearch Suggestions spec defines a JSON format that’s incompatible with JQueryUI’s autocomplete. Here’s a way to make it work.

JQueryUI Autocomplete plugin expects results to come back as a flat array, e.g.

["comme", "comment", "communication", "committee"]

But the OpenSearch Suggestions spec returns an array of 2-4 elements, which include at least the original term, and the array of completions:

["comm", ["comme", "comment", "communication", "committee"]]

Try to hook them up as-is, and JQueryUI’s autocopmlete will only see the term itself as a suggestion. Not an extremely helpful suggestion.

We can override autocomplete’s source function to pull out the array from the JSON response (as of JQuery 1.9 / JQueryUI 1.10):

        source: function(request, response) {
                url: "http://en.wikipedia.org/w/api.php",
                dataType: "jsonp",
                data: {
                    'action': "opensearch",
                    'format': "json",
                    'search': request.term
                success: function(data) {

Try it live on jsfiddle.net

Note that we can’t just use a response listener, as the array of suggestions in the 2nd position has already been flummoxed by that point. We have to do the whole request/response manually via a custom source function.

Thanks to Andrew Whitaker for mentioning this in the process of answering a StackOverflow question on transitioning JQuery versions.