Here is the way we initialize autocomplete (jQuery) for dynamically inserted element:
$(function() {
setTimeout(function(){
$("[id^='requisition_material_items_attributes_'][id$='_item_name_autocomplete']").each(function (){
$(this).autocomplete({
minLength: 1,
source: $(this).data('autocomplete-source'),
select: function(event, ui) {
$(this).val(ui.item.value);
}
});
});
}, 5000);
});
Here setTimeout
(5 second delay) allows autocomplete initialization for first dynamically inserted element. However the initialization does not work for second inserted element and the autocomplete does not kick in for second element. How to fix the JS code above to make it working for second elements and on?
Update
The solution provided by jQuery autocomplete for dynamically created inputs (so called duplicate case) is not working here because it is for a different issue. In duplicate case the problem was solved by adding the initialization of autocomplete when the new element was generated with JavaScript. In our case, the new element was generated by Rails and can not be inserted with autocomplete initialization code into it when generating. In our case autocomplete works for first inserted element and does not for second element. Our question is to make autocomplete initialize for second element and on.
Update
Rails view for item_name_autocomplete:
<%= f.input :item_name_autocomplete, :label => t("Item Name"), :input_html => { data: {autocomplete_source: SUBURI + base_materialx.autocomplete_parts_path}},:placeholder => t("Enter Part Name Keyword"), :required => true %>