2017-04-22 119 views
0

我發現通過jquery動態創建文本框的代碼,也發現通過javascript實現文本框的自動完成功能。自動完成功能無法動態添加文本框

但合併它們對我來說是一個問題。第一個文本框已成功實施自動完成..但新的動態創建文本框,通過添加按鈕不實現autocomplete..here是我的代碼

<script type="text/javascript"> 
    $(function() { 
     var availableTags = [ 
    "ActionScript", 
    "AppleScript", 
    "Asp", 
    "BASIC", 
    "C", 
    "C++", 
    "Clojure", 
    "COBOL", 
    "ColdFusion", 
    "Erlang", 
    "Fortran", 
    "Groovy", 
    "Haskell", 
    "Java", 
    "JavaScript", 
    "Lisp", 
    "Perl", 
    "PHP", 
    "Python", 
    "Ruby", 
    "Scala", 
    "Scheme" 
]; 
     $(".insti_name").autocomplete({ 
      source: availableTags, 
      autoFocus:true 
     }); 
    }); 
    $(document).ready(function() { 
var max_fields  = 10; //maximum input boxes allowed 
var wrapper   = $(".input_fields_wrap"); //Fields wrapper 
var add_button  = $(".add_field_button"); //Add button ID 

var x = 1; //initlal text box count 
$(add_button).click(function(e){ //on add input button click 
    e.preventDefault(); 
    if(x < max_fields){ //max input box allowed 
     x++; //text box increment 
     $(wrapper).append('<br><div><input class="insti_name" type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box 
    } 
}); 

$(wrapper).on("click",".remove_field", function(e){ //user click on remove text 
    e.preventDefault(); $(this).parent('div').remove(); x--; 
}) 
}); 
    </script> 

    <br><br> 

<div class="input_fields_wrap"> 
    <button type="button" class="btn btn-primary btn-lg add_field_button " > 
    ADD INSTITUTIONS</button><br> 
<div style="margin-top:11px"><input class="insti_name" type="text" 
    name="mytext[]"></div> 
    </div> 
+0

添加事件處理程序以在您添加新元素之後綁定到您的類。 – ochi

回答

0

自動完成插件API不支持你正在尋找出來的動態行爲但我們可以使用下面的代碼實現相同的功能:

$(add_button).click(function(e){ //on add input button click 
    e.preventDefault(); 
    if(x < max_fields){ //max input box allowed 
     x++; //text box increment 

     // first destroy the previously setup auto-complete 
     $(".insti_name").autocomplete("destroy"); 

     // append your new html element 
     $(wrapper).append('<br><div><input class="insti_name" type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box 

     // setup autocomplete again 
     // you can move this call and the one above (the one you have set earlier) in one function for better maintainability 
     $(".insti_name").autocomplete({ 
      source: availableTags, 
      autoFocus:true 
     }); 
    } 
}); 

確實有效。希望能幫助到你!

+0

@nitin請標記爲解決方案,如果它爲你工作。 –

相關問題