Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typeahead and Bloodhound - how to get JSON result

I have the json list of Countries: http://vocab.nic.in/rest.php/country/json

And I'm trying to get country_id and country name with Bloodhound suggestion engine. O tried following code:

var countries = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('country_name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    limit: 10,
    prefetch: {
        url: 'http://vocab.nic.in/rest.php/country/json',
        filter: function(response) {
            return response.countries;
        }
    }
});

$('#my-input').typeahead({
        hint: true,
        highlight: true,
        minLength: 1
    },
    {
        name: 'states',
        displayKey: 'value',
        source: countries.ttAdapter()
    });

Which doesn't work. How should I change the code to make this work?

like image 990
user1049961 Avatar asked Mar 29 '14 11:03

user1049961


2 Answers

// instantiate the bloodhound suggestion engine
var countries = new Bloodhound({  
  datumTokenizer: function(countries) {
      return Bloodhound.tokenizers.whitespace(countries.value);
  },
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  remote: {
    url: "http://vocab.nic.in/rest.php/country/json",
    filter: function(response) {      
      return response.countries;
    }
  }
});

// initialize the bloodhound suggestion engine
countries.initialize();

// instantiate the typeahead UI
$('.typeahead').typeahead(
  { hint: true,
    highlight: true,
    minLength: 1
  }, 
  {
  name: 'countries',
  displayKey: function(countries) {
    return countries.country.country_name;        
  },
  source: countries.ttAdapter()
});

Example Codepen

Typeahead Output

Output of Typeahead

Notes:

  • data on your server = "prefetch".
  • data from outside = "remote"
like image 176
Jens A. Koch Avatar answered Oct 11 '22 13:10

Jens A. Koch


NOTE: if you do all this and it still is not working examine your data.json file (whatever you have named it)

example of good format: https://github.com/twitter/typeahead.js/blob/gh-pages/data/countries.json

['data1','data2',.....]

I was tripped up on out of place quote.

like image 22
Michael Nelles Avatar answered Oct 11 '22 12:10

Michael Nelles