Twitter Bootstrap:无匹配项的Typeahead功能

6
我有一个“添加新事物”的表单,需要将“用户”与“事物”关联起来。
我使用Twitter Bootstrap Typeahead在输入时提供用户列表。如果用户在列表中,就可以选择它。
但是,如果用户不存在,我想让“创建新用户”链接出现。
因此,基本上我需要在`.typeahead()`中某处添加“无匹配项”的功能,但我无法解决它。
2个回答

4

扩展typeahead类:

var newusertext = 'New user';
var newuserlink = '/add/user/0';

$.fn.typeahead.Constructor.prototype.process = function (items) {
      var that = this

      items = $.grep(items, function (item) {
        return that.matcher(item)
      })

      items = this.sorter(items)

      if (!items.length) {
         return this.rendernonmatch().show()
      }

      return this.render(items.slice(0, this.options.items)).show()
    } 


$.fn.typeahead.Constructor.prototype.rendernonmatch = function () {
      var that = this
      var items = new Array();
      items.push(newusertext)
      items = $(items).map(function (i, item) {
        i = $(that.options.item).attr('data-value', item)
        i.find('a').html(that.highlighter(item))
        return i[0]
      })
      items.first().addClass('active')
      this.$menu.html(items)
      return this
    }

/* redirect to the registration page to add a new user */    
$.fn.typeahead.Constructor.prototype.updater = function (item) {
      if(item === newusertext){ window.location =  newuserlink; return}
      return item
    }      

请查看: http://bootply.com/66630

0
我使用了typeahead的“notFound”选项中的“template”,从那里我可以设置一个链接按钮,对我来说更加方便。Typeahead设置:
$('#remote .typeahead').typeahead({
    hint: true,
    highlight: true,
    minLength: 2
  },
  {
    name: 'sn-tags',
    display: 'tag',
    source: oBusqTags, //Bloodhound object
    templates: {
      notFound: '<p>No matches<br><a id="btnAddNewTag" href="#">Add New Tag</a></p>'
    }
}).bind("typeahead:select", function(obj, datum, name) {
  //add selection as an option on a select element
  $('#lbxAddTag').append($('<option>', {
    value: datum.id,
    text: datum.tag
  }));
});

这是该链接的监听器:

$('#remote').on('click', '#btnAddNewTag', function(e){
    $('#lbxAddTag').append($('<option>', {
        value: "0",
        // this is tricky, as there aren't any matches then 
        // $('#remote .typeahead').typeahead('val') contains '', 
        // so i had to set an id for the typeahead input text box and 
        // 'manually' get its value
        text: $('#tbxBusqTag').val()
    }));
    // as the text is already added as a select option
    // i clean the typeahead input box
    $('#remote .typeahead').typeahead('val','');
    e.preventDefault();
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接