I am adding html dynamically using jQuery and I use an autocomplete on this content. However the autocomplete does not work on the dynamically added content. I have seen many similar questions to mine but their solutions don’t seem to work for me. The jQuery code I have is:
$(document).ready(function() {
if ( $("#add-sister-centers").length > 0 ){
$(".autocomp_centers").autocomplete({
serviceUrl:'/suggest_centers',
maxHeight:400,
width:252,
minChars:2,
onSelect: function(value, data){ $("input[name='center_ids[]']").val(data); }
});
$("#add-another-button").click( function(){
var sister_center_input = "<div class=\"field\" style=\"margin-top:10px;\"><span class=\"purple-text\" style=\"font-weight:bold; margin-right:20px;\">Center name*</span><input type=\"text\" name=\"center_names[]\" class=\"autocomp_centers\"/></div>"
sister_center_input.autocomplete();
$("#additional-sister-centers").append(sister_center_input);
});
}
});
What am I doing wrong? Should I be using bind, live or on?
The problem is that your variable:
sister_center_inputis just a string variable, but you are trying to use the jQueryautocompletemethod from it. That will never work.You also have to pass the same properties for the autocomplete function that you defined in the definition above.
Change the second part of your code to look like this and try it: