Antrikshy Antrikshy - 7 months ago 10
Javascript Question

How can I get Typeahead.js to autocomplete or select using one field of an object and not all of it?

I currently have this code to set up Typeahead:

var people = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace("personName"),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: generateCastDb()
});

$('#app-container .search-box').typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
name: 'people',
source: people,
templates: {
suggestion: function (data) {
return '<p>' + data["personName"] + '</p>';
}
}
});


generateCastDb
returns an array of objects similar to this:

{personId: "293", personName: "Roger Pratt", appearances: [{mediaId: "11834", mediaType: "movie", characterName: "Man Living in Barrel"}]}


As you can see, I am using this
personName
field for Typeahead's autocomplete suggestions. The dropdown appears perfectly well, but when I select one of the options (using arrow keys or mouse), the entire object appears in the input box instead of just the
personName
value.

How can I make the search box update using just that one field instead of the entire object? I have tried using
jQuery.val()
to set it when the
typeahead:selected
event fires, but it doesn't work.

Answer

You are missing the displayKey attribute

$('#app-container .search-box').typeahead({
    hint: true,
    highlight: true,
    minLength: 1
  }, {
    name: 'people',
    source: people,
    displayKey: 'personName', // <---- this noe
    templates: {
      suggestion: function(data) {
        return '<p>' + data["personName"] + '</p>';
      }
    }
  });
});

displayKey can also be replaced by display like this

display: function(item){
    return item.personName;
}
Comments