Yshmarov
Yshmarov

Reputation: 3749

Gem usage: cocoon + selectize-rails

I can't make selectize-rails work with cocoon. (When adding +1 attendance selectize is not active for it). I saw this question, but it brought me nowhere.

What I have:

- Attendance model
- Event model
- Event has_many :attendances

My js:

$(document).ready(function(){
    if ($('.selectize')){
        $('.selectize').selectize({
            sortField: 'text'
        });
    }
});

Events/_form:

= simple_form_for @event do |f|
   = f.button :submit, class: "btn btn-success add-button"
   = f.input :starts_at, :minute_step => 15
  #tasks
    = f.simple_fields_for :attendances do |attendance|
      = render 'attendance_fields', f: attendance
    .links
      %p
      = link_to_add_association 'Add attendance', f, :attendances

_Attendance_fields:

.nested-fields
  = f.select :guest_id, Guest.all.map{|c| [c, c.id]}, {},class: 'selectize'
  = link_to_remove_association "Remove attendance", f

Any ideas? Please help

Upvotes: 1

Views: 418

Answers (1)

nathanvda
nathanvda

Reputation: 50057

So your code selects the items of class .selectize on the page and then calls the selectize function on them. However, this call is only run upon initial load of the page. When new items are added dynamically to the page, you will have to do that again. Cocoon raises events, to which you can listen, and when they happen, you get the piece of html that was inserted.

So you could do something like:

$('form').on('cocoon:after-insert', function(e, addedItem) {
  $(addedItem).find('.selectize').selectize({
    sortField: 'text'
  })
});

This means: everytime somewhere in the form the cocoon event is raised, we will apply the .selectize code.

More examples and information can be found in the documentation.

Upvotes: 4

Related Questions