简体   繁体   中英

jQuery typeahead stops working when I select an option from the dropdown

I'm using jQuery typeahead to do an autocomplete that works perfect at first, but when I select an option from the list and then I try to use it again (by typing in the input) it simply doesn't show results again.

Looks like typeahead get destroyed when I select an option.

Update #1

I've created a jsfiddle to you to be able to see what's happening, you can type "someone" in the input to get autocompleted data: http://jsfiddle.net/cristiangrojas/rhtd9o8k/3/

var Opportunities = new Bloodhound({
  datumTokenizer: function(d) {
    return Bloodhound.tokenizers.whitespace(
      '{id} {name} {identification} {email} {vehicle_registration}'.assign({
        "id": d["id"],
        "name": d["name"],
        "identification": d["identification"],
        "email": d["email"],
        "vehicle_registration": d["vehicle_registration"]
      })
    );
  },
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  local: opportunities
});

Opportunities.initialize();

$('input[name="opportunities_search"]').typeahead({
  hint: true,
  highlight: true,
  minLenght: 1
}, {
  name: 'oportunidades',
  displayKey: 'id',
  source: Opportunities.ttAdapter(),
  templates: {
    empty: [
      '<div class="empty-message">',
      'No se encontró ninguna oportunidad',
      '</div>'
    ].join('\n'),
    suggestion: Handlebars.compile(
        '<p>' +
        'Opp #{{ id }}' +
        '<br>' +
        '{{ name }}' +
        '<br>' +
        'CC: {{ identification }}' +
        '<br>' +
        'email: {{ email }}' +
        '<br>' +
        'Placa: {{ vehicle_registration }}' +
        '</p>'
    )
  }
});

From the docs:

https://github.com/twitter/typeahead.js/blob/master/doc/jquery_typeahead.md

displayKey – For a given suggestion object, determines the string representation of it. This will be used when setting the value of the input control after a suggestion is selected. Can be either a key string or a function that transforms a suggestion object into a string. Defaults to value

You are using a key string of 'id', but your json data for id is not a string its a number. So either change your json data to have the id as a string or use a function to return the id as a string as in this fiddle:

displayKey: function(d){return d.id+'';},

http://jsfiddle.net/rhtd9o8k/19/

Where d is the suggestion object returned and appending an empty string to the id attribute is an easy way to cast a number to a string in javascript.

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