재우니의 블로그

autocomplete 사용할 경우, 동적 dom 생성시 매번 이벤트를 지정해 줘야 한다.

dom 을 append 하고 나서, 추가된 마지막 dom 에 :last 하여 autocomplete() 함수를 지정하는 구문이다.





<div class="input_fields_wrap">
<button class="add_field_button">Add More Fields</button>
<div><input type="text" name="mytext[]"></div>
</div>


<script>
$(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
var availableAttributes = [
"account_address",
"account_address_city",
"account_address_country",
"account_address_state",
"account_address_street1",
"account_address_street2",
"account_address_zip",
"account_email",
"account_login",
"account_name",
"account_number",
"account_telephone"
];
$(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('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>');
$(wrapper).find('input[type=text]:last').autocomplete({
source: availableAttributes
}); 
//add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault();
$(this).parent('div').remove();
x--;
})
$("input[name^='mytext']").autocomplete({
source: availableAttributes
}); 
});

// autocomplete enablement
</script>