Search code examples
javascriptjqueryautocompletecocoon-gem

Dynamically generated fields (cocoon) and autocomplete


I am using cocoon js and trying to get autocomplete working. As of right now, autocomplete only works on the initial field. Upon clicking 'add field' the autocomplete still only works on the first field.

formulation.coffee

$('.formulation_line_item_dna_name').focus ->
  $(this).autocomplete
    minLength: 2,
    source: ['foo', 'food', 'four']

formulation.html.erb

...
<div class="formulation_line_items">
  <%= f.label :dna_name, "DNA", :class => "col-md-1 control-label unbold" %>
  <div class="col-md-3">
    <%= f.text_field :dna_name, :class => 'formulation_line_item_dna_name' %>
  </div>
</div>
...
<div class="add-more-formulation-line-items">
  <%= link_to_add_association 'Add Formulation Line Item', f, :formulation_line_items, 
      :class => 'btn btn-success' unless params[:command] == 'create child' %>
</div>
...

Upon inspection it appears that the additional line items are not appending the ui-autocomplete-input class. I tried manually adding 'ui-autocomplete-input' to all dynamically generated fields but that did not work.

I have also tried adding

$('.add_fields').click ->

in my formulation.coffee file. This still only allowed for autocomplete on the first, static field.


Solution

  • I was able to successfully allow autocomplete on dynamically generated fields by using cocoon callbacks such as:

    $(document).ready(function(){
      $('.formulation_line_items')
        .on('cocoon:after-insert', function() {
          var tags = ["foo","foobar","foobaz"];
          $('.formulation_line_item_dna_name').focus(function(){
            $(this).autocomplete({
               minLength: 2,
               source: tags
                });
        });
      })  
    });