自动完成功能无法动态添加文本框
问题描述:
我发现通过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>
答
自动完成插件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请标记为解决方案,如果它为你工作。 –
添加事件处理程序以在您添加新元素之后绑定到您的类。 – ochi