jQuery: Using AutoComplete on dynamically created elements
This is a common problem wherein you dynamically create your DOM elements using jQuery. The $(document).ready(function(){}); would already be initialized — without the newly created DOM. So to go around this issue, I have posted this sample code as reference:
< script type="text/javascript" >
<!--
var myAutoComplete = null; //STEP 1) INITIALIZE
$(document).ready(function(){
//for adding more users
myAutoComplete = function () { //STEP 2) CREATE THE FUNCTION
$(".user").autocomplete("<?=$this->baseUrl?>/access/shortnames", { width: 162, selectFirst: false });
$(".user").result(function(event, data, formatted) {
//alert($(this).parent().find(".account_id").val());
if (data) {
//the the class account_id inside the parent div and then put the returned data from the autocomplete
$(this).parent().find(".account_id").val(data[1]);
//$("#account_id").val(data[1]);
}
});
}
//for the groups
$("#group").autocomplete("< ?=$this->baseUrl?>/group/groups", { width: 252, selectFirst: false });
$("#group").result(function(event, data, formatted) {
if (data)
$("#group_id").val(data[1]);
});
//for the addmore button
$("#addmore").click(function() {
newdiv = $("#parent_div").clone().appendTo("#shortname_container");
newdiv.find(".user").val('');
newdiv.find(".account_id").val('');
myAutoComplete(); //STEP 3) CALL THE FUNCTION AFTER THE ACTION
});
myAutoComplete(); //STEP 4) CALL THE FUNCTION FOR THE FIRST LOADING
});
-->
< /script >
Post Tags: jquery
Browse Timeline
- « jQuery: A quick and dirty tutorial on DOM traversing using parent() and classname selectors
- » Bill Karwin: ActiveRecord does not suck