Twitter Bootstrap: функция опережающего ввода для отсутствия совпадений

У меня есть форма «добавить новую вещь», которая связывает «пользователя» с «вещью».

Я использую Twitter Bootstrap Typeahead, чтобы выводить список пользователей по мере ввода.
Он отлично работает, если пользователь есть в списке, я могу его выбрать.

Но если пользователь не существует, я бы хотел, чтобы появилась ссылка «Создать нового пользователя».

В общем, мне нужна какая-то функция «нет совпадений» где-то в .typeahead(). Я не могу это решить.


person Jason Varga    schedule 15.02.2013    source источник


Ответы (2)


Расширьте класс 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.

person Bass Jobsen    schedule 07.07.2013

Я использовал параметр typeahead notFound 'template', оттуда я мог установить кнопку ссылки, которая для меня более доступна. Настройки опережающего ввода:

$('#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();
});
person JuanVS    schedule 12.05.2017