Make jQuery autocomplete plugin accept json

Just wanted to quickly share a little hack, if you will, that makes the jQuery autocomplete plugin to accept json output.

Now the plugin is of course deprecated, so the smart thing is to upgrade to its successor.
Sometimes, however, an upgrade is not an option. 🙁
For times like these, when you need the plugin to accept json, here’s a little snippet that should help you out:

$("#your-id-here").autocomplete('url', {
            minChars: 1,
            width: 600,
            matchContains: true,
            autoFill: false,
            cacheLength: 1,
            max:300,
            parse: function(data) {
                var parsed = [];                
                $.each(JSON.parse(data),function(i, item) {
                    parsed[i] = {
                        data: item,
                        value: formatText(item, i),
                        result: formatText && formatText(item, i) || item
                    }
                });
                return parsed;  
            },
            formatItem: formatText,
            formatResult: formatText
    });
   
    function formatText(item, i, max) {
        console.log(item);//this should be your json output
        return "your formatted text here";
    }

So, your regular options, and ‘parse’ which overrides the plugin’s parse method.
Hopefully this makes sense and proves useful.

RSS feed for comments on this post. TrackBack URI

Leave a Reply