Why are the typeahead suggestions undefined?
Asked Answered
U

2

6

Hopefully this is not a duplicate of: Why does bloodhound.get() return undefined?

I upgraded to typeahead.js version 0.10.0. Prior versions were returning the suggestions properly. Now I am getting an undefined return with the below code:

// instantiate the bloodhound suggestion engine
var engine = new Bloodhound({
    datumTokenizer: function (d) { return [d]; },
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    local: ["(A)labama", "Alaska", "Arizona", "Arkansas"]
});

// initialize the bloodhound suggestion engine
engine.initialize();

$('#typeahead').typeahead(null, {
        source: engine.ttAdapter()
    });

Here is my fiddle: http://jsfiddle.net/ucUcn/6/

Any ideas why this is happening?

Univalent answered 8/2, 2014 at 17:21 Comment(0)
G
9

The local array must contain objects, not strings themself.

// instantiate the bloodhound suggestion engine
var engine = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('d'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: [{
    d: "(A)labama"
  }, {
    d: "Alaska"
  }, {
    d: "Arizona"
  }, {
    d: "Arkansas"
  }]
});

// initialize the bloodhound suggestion engine
engine.initialize();

$('#typeahead').typeahead(null, {
  displayKey: 'd',
  source: engine.ttAdapter()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js"></script>
<input id="typeahead" />

Fiddle with above fix:

JsFiddle

Guardado answered 8/2, 2014 at 19:52 Comment(2)
It works great when you type an A but if you type Ar it disappearsBowne
it looks like my link to typeahead is pointing to the latest version and there was breaking changes. Going to leave the updated version linked because in an ideal world you would be using the updated version.Guardado
C
1

As @Chad said, the result array must contains objects.

I only wanted to add that the default value used to display the suggestion is value

So you could do something like

var suggestionEngine = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: "myUrl",
        filter: function (suggestions) {
            var mappedResult = $.map(suggestions[1], function(suggestion) {
                return { value : suggestion }
            });

            return mappedResult;
        }
    }
});
Canoe answered 23/1, 2015 at 14:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.