A web developer's blog. PHP, MySQL, CakePHP, Zend Framework, Wordpress, Code Igniter, Django, Python, CSS, Javascript, jQuery, Knockout.js, and other web development topics.

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 >
This entry was posted in General and tagged . Bookmark the permalink.

One Response to jQuery: Using AutoComplete on dynamically created elements

  1. Dinesh Sailor says:

    Thanks, that’s cool solution.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>