简体   繁体   中英

Can I have typeahead/bloodhound always show what the user is typing?

I am implementing a tags input using typeahead/bloodhound. Users are able to add new tags, they are not constrained to the ones that already exist.

I would like to always show what the user is typing in the suggestion list, so they can create a tag by clicking on it (currently they can do so by typing a comma or typing enter). Ideally I would be able to differentiate new from existing tags with a little badge next to the "suggestion" that says new.

Is it possible to do this (and if so, how)?

The code I have right now, which works fully (other than not showing what is being typed in the dropdown):

var tags = new Bloodhound({
  datumTokenizer: Bloodhound.tokenizers.obj.whitespace('name'),
  queryTokenizer: Bloodhound.tokenizers.whitespace,
  prefetch: {
    url: '/Tags/list.json',
    cache: false,
    filter: function(list) {   
      return $.map(list, function(tag) {
        return { name: tag }; });
    }
  }
});
tags.initialize();
}

$('.tags-wrapper input').tagsinput({
  typeaheadjs: {
    name: 'tags',
    displayKey: 'name',
    valueKey: 'name',
    source: tags.ttAdapter(),
  }
});

I figured it out!

Firstly I added:

templates: {
    empty: function(obj) {return '<div class="tt-suggestion tt-selectable tt-current-query">'+obj.query+' <span class="tt-new badge badge-info">New</span></div>';}
}

to $('.tags-wrapper input').tagsinput({ ...

then I added some new jquery to detect when the user clicks on a new tag

$(document).on("click", ".tt-current-query", function() {
    var input=$(this).closest('.twitter-typeahead').find('input.tt-input');
    input.trigger("keypress");
});

I am not 100% sure why this works with just a keypress trigger, but it does! I would be interested to know why this works - I spent a while trying to inject a comma or return keypress event and eventually stumbled upon this solution.

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