Reputation: 935
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?
Upvotes: 1
Views: 955
Reputation: 18168
The problem is that your variable: sister_center_input
is just a string variable, but you are trying to use the jQuery autocomplete
method 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:
$("#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>"
$("#additional-sister-centers").append(sister_center_input);
$('.autocomp_centers').autocomplete({
serviceUrl:'/suggest_centers',
maxHeight:400,
width:252,
minChars:2,
onSelect: function(value, data){ $("input[name='center_ids[]']").val(data);}
});
});
Upvotes: 1
Reputation: 988
first thing, you can apply autocomplete plugin to text box only. second, your newly created textbox has not been rendered before you are trying to apply autocomplete on it. Also, sister_center_input is just a string variable which doesn't contain any DOM, hence it can not apply autocomplete on a string. try below mentioned code
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>");
$("#additional-sister-centers").append(sister_center_input);
$("#additional-sister-centers").find(".autocomp_centers").autocomplete();
Upvotes: 1