我找到了通过jquery动态创建文本框的代码,还发现通过javascript在文本框上实现自动完成。
但将它们合并在一起对我来说是一个问题。第一个文本框已成功实现自动完成,但按添加按钮新创建的动态文本框不会实现自动完成。这是我的代码
<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 :(得分: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
});
}
});
这肯定有用。希望它有所帮助!