Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are the typeahead suggestions undefined?

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?

like image 722
core Avatar asked Feb 08 '14 17:02

core


2 Answers

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

like image 71
Chad Carisch Avatar answered Sep 28 '22 02:09

Chad Carisch


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;
        }
    }
});
like image 36
RPDeshaies Avatar answered Sep 28 '22 01:09

RPDeshaies