How to initialize autocomplete for multiple dynamically inserted element?
In our Rails 3.2 app, a autocomplete field item_name_autocomplete is inserted onto the form when user clicks Insert button. After insertion, the user can do autocomplete with the field. The id of the inserted item_name_autocomplete is unique and dynamically assigned when the element gets inserted. Here is the Rails view code to create html:
<%= f.input :item_name_autocomplete, :label => t("Item Name"), :input_html => { data: {autocomplete_source: SUBURI + base_materialx.autocomplete_parts_path}} %>
Here is the jquery code to initialize the autocomplete. The setTimeout play the trick for initializing 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); });
The problem we are having is that the initialization js code can only initialize the first inserted element.
It does not initialize for the 2nd inserted element and on. Also we can not do initialization when the element
is generated because of the view code is created by Rails. Is there a way we can make all elements after first one to be initialized?