2017-08-25 49 views
1

由於各種原因,我需要能夠上下文複製輸入框。每次用戶添加另一次旅程時,如何初始化另一個typeahead.js實例?我似乎不能在。對()如何在多個div元素和上下文上初始化typeahead.js?

這是我當前的代碼以將其初始化:

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, 
     }); 
}); 
+0

您是否嘗試在動態創建的輸入上初始化typahead?你有沒有試過克隆它? – azs06

回答

1

我建議創建一個函數將爲給定實例設置預先輸入。 然後爲每個新創建的實例調用該函數。

$(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, 
     }); 
} 
+0

謝謝。我可以問爲什麼你需要在添加操作之外擁有setupState? –

+0

@HC因爲您想在初始狀態的添加操作之外調用它。請參閱'setupState($('。state'))'。 –

相關問題