如何在多个div元素和上下文中初始化typeahead.js?

时间:2017-08-25 18:46:34

标签: javascript jquery typeahead.js typeahead

由于各种原因,我需要能够在上下文中复制输入框。每次用户添加另一个行程时,如何初始化另一个typeahead.js实例?我似乎无法在.on()

中初始化它

这是我目前的代码:

HTML:

<form>
    <div class="summary">
        <div class="trip">
          <input class="state tt-input">
          ... other code ...
        </div>
        ...
    </div>
    <button type="button" id="add">Add another trip</button>
</form>

jquery的:

$(document).ready(function() {

  var additional = $('.trip').html();

  $('form').on("change", '.state', function(e){
      var $contextualDiv = $(e.target).closest('div');
      var $state = $contextualDiv.find('.state');
  });

  $('#add').click(function() {
    if ($('.summary').children().length >= 5) return;
    $('.summary').append('<div class="trip">' + additional + "<div>");
  });

  $('.state').typeahead( //or $state.typeahead (that doesn't seem to work)
     {
        hint: true,
        highlight: true,
        minLength: 1
     },
     {
        name: 'states',
        source: bh,
      });
});

1 个答案:

答案 0 :(得分:1)

我建议创建一个函数,为给定的实例设置typeahead。 然后为每个新创建的实例调用该函数。

$(document).ready(function() {

  var additional = $('.trip').html();


  $('#add').click(function() {
    if ($('.summary').children().length >= 5) return;
    var new_trip = $('<div class="trip">' + additional + "<div>")
    $('.summary').append(new_trip);
    var state = new_trip.find('.state')
    setupState(state)
  });

  setupState($('.state'))
});

function setupState(state){
    state.typeahead(
     {
        hint: true,
        highlight: true,
        minLength: 1
     },
     {
        name: 'states',
        source: bh,
      });
}