Search code examples
jsonpbootstrap-typeaheadtypeaheadtypeahead.js

Typeahead result formatting


Trying to use Typeahead and struggling with JSON formatting (which I have no control over).

{ name="Long Island", type="2", id="1234"}

Here is my JS

$autocomplete.typeahead({
name: 'location',
remote: {
    url: 'http://pathtomysite.com/%QUERY?',
    dataType: 'jsonp',
    filter: function (parsedResponse) {
        console.log(parsedResponse);
        return parsedResponse;
    }
},
template: [
    '<p class="repo-name">{{name}}</p>',
    '<p class="repo-description">{{id}}</p>'
].join(''),
engine: Hogan

});

So the request works and it returns objects in the console, but the typeahead visual dropdown just says 'undefined'.

So I am guessing I need to do something with datums?

I've tried using Hogan templating but nothing is appearing in the drop down.

Not sure if JSONP is this issue? The request has a load of characters prepended, see the JS tab http://jsbin.com/aPOZohi/1/edit

So yeah, where am I going wrong?

Once I get it returning data, I have another formatting question for you :)


Solution

  • @Xeevis's answer is almost correct.

    First: the "many characters prepended" are jQuery's way of doing JSONP internally when doing cross-domain request.

    Second: Xeevis is right, the problem is valueKey, but not only valueKey. The response has to be an array of object, each containing a member by the name specified by valueKey. So set valueKey to "name", but also return an array:

    filter: function (parsedResponse) {
        console.log(parsedResponse);
        return parsedResponse.locations;
    }