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?

Community
  • 1
  • 1
core
  • 851
  • 1
  • 8
  • 28

2 Answers2

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

Chad Carisch
  • 2,422
  • 3
  • 22
  • 30
  • It works great when you type an `A` but if you type `Ar` it disappears – JP Hellemons Jun 20 '14 at 13:03
  • 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. – Chad Carisch Jun 20 '14 at 14:17
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;
        }
    }
});
RPDeshaies
  • 1,826
  • 1
  • 24
  • 29