Default suggestions for Twittera fonts: how to get the first suggestions in a preselected array?

I am using Twitter Typeahead and I would like to offer some values โ€‹โ€‹to the user when the input field gets focus before anything is typed.

Here's an example of this on the default page:

var nflTeams = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('team'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  identify: function(obj) { return obj.team; },
  prefetch: '../data/nfl.json'
});

function nflTeamsWithDefaults(q, sync) {
  if (q === '') {
    sync(nflTeams.get('Detroit Lions', 'Green Bay Packers', 'Chicago Bears'));
  }

  else {
    nflTeams.search(q, sync);
  }
}

$('#default-suggestions .typeahead').typeahead({
  minLength: 0,
  highlight: true
},
{
  name: 'nfl-teams',
  display: 'team',
  source: nflTeamsWithDefaults
});

      

However, in this example, they are hard-coding the values โ€‹โ€‹they want to suggest:

      sync(nflTeams.get('Detroit Lions', 'Green Bay Packers', 'Chicago Bears'));

      

In my case, I am using Bloodhound with pre-fetch, and I want to suggest the first few options returned by the prefetch.

Edit: What I would like to show are the first few items returned by the server. The server will be responsible for the order in which they are displayed. So in the above example, if data / nfl.json contains:

[
{ "team": "San Francisco 49ers" },
{ "team": "Chicago Bears" },
{ "team": "Cincinnati Bengals" },
{ "team": "Buffalo Bills" },
{ "team": "Denver Broncos" },
{ "team": "Cleveland Browns" },
...

      

I would just show everything that is in the first commands. The number of commands shown can be a parameter.

How should I do it?

+3


source to share


1 answer


For example, you want to display the first 2 items by default



function nflTeamsWithDefaults(q, sync) {
    if (q === '') {
        sync(nflTeams.all().slice(0, 2)); // slice(start,end)
    }
    else {
        nflTeams.search(q, sync);
    }
}

      

+4


source







All Articles