简体   繁体   中英

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM