Andy Harvey
Andy Harvey

Reputation: 12653

Rails autocomplete works in parent but not nested form. Why?

in a Rails 3.2 app with JEE, I am trying to implement an autocomplete field a la Railscast #102, within a complex nested form using Cacoon.

I have managed to get similar autocomplete field working perfectly on the parent form. However I can not get the autocomplete to work on the nested form. It appears that the javascript is not being triggered.

My form looks something like

<%= form_for @parent do |f| %>
<%= f.text_field :name, :class=>"parent-name", :data => {:autocomplete_source => Model.order(:name).map(&:name) } %>
  <%= f.fields_for :children  do |child| %>
    <%= f.fields_for :grand_children do |grand_child| %>
      <%= f.text_field :name, :class=>"grand-child-name", :data => {:autocomplete_source => Model.order(:name).map(&:name) } %>
    <% end %>
  <% end %>
<% end %>

I have two javascript functions

$(function() {
    $('.parent-name').autocomplete({
        source: $('.parent-name').data('autocomplete-source')
    });
});

$(function() {
    $('.grand-child-name').autocomplete({
        source: $('.grand-child-name').data('autocomplete-source')
    });
}); 

The parent autocomplete is working perfectly, the grandchild is not. Am I missing something? Is there a reason that this would not work in a nested form? Or have I made a mistake in my approach?

Grateful for any pointers.

EDIT

The grand-child elements is being added asynchronously, the parent element is being rendered on page load. This appears to be the key to the issue. When I open an existing record to edit (i.e. fields are rendered and populated on page load) the autocomplete is functioning on these fields.

SOLUTION

Thanks to Chris Drappier who pointed me in the right direction. He said I need to add my observer when adding the new form element.

I now have two jquery functions. The original

$(function() {
    $('.grand-child-name').autocomplete({
        source: $('.grand-child-name').data('autocomplete-source')
    });
});

and

$(function() {
    $(document).on("focus",".grand-child-name", function() {
        $('.grand-child-name').autocomplete({
            source: $('.grand-child-name').data('autocomplete-source')
        }); 
    });
})

While Chris pointed me towards the .live() function, apparently this is being depreciated, and .on(focus) provides the correct functionality.

Thanks Chris!

Upvotes: 2

Views: 1109

Answers (1)

Chris Drappier
Chris Drappier

Reputation: 5370

This is a tricky one, but I believe the problem is that you have to add your observer when you add the new form element as well. if you are using jquery, there is functionality to handle this case. see the api docs in jquery for live() . I think that should get you where you need to be.

Upvotes: 3

Related Questions