Search code examples
jqueryruby-on-railsselectize.jscocoon-gem

"selectize-dropdown-content" empty after dynamically creating new div


I'm using Rails, JQuery, Cocoon, and Selectize to create a form on a page. The application is used to create a menu for a restaurant.

/menu/new gives you a page where you can enter the menu name (e.g. "Lunch") as well as a button that says "add menu items", and a "create menu" button. The idea is that when you click to add a menu item, a form appears with fields for Category, Item name, Price, and Description. You can add as many menu items as you want.

My issue isn't one of functionality because everything works fine. The create action will create the Menu, Menu Items, and Menu Item Categories as desired. My issue is with Selectize.

Clicking "add new menu item" gives you the form for a menu item as I mentioned earlier, and in that form "Category" is a drop-down list of previously created categories. The problem is, the list is only populated for one of the forms on the page at a time:

Like so

As you can see, only the newest form displays any data in the Category drop-down. The first two that appear on the page are now blank. The data is still there, but it is not visible. I can't figure out how to get the previous Menu Item forms to show the list of categories.

This is purely cosmetic, as the data will save correctly if I hit 'create menu'. But it does make it a pain if you want to edit the category after clicking to add a new menu item.

Here's the JQuery:

$('form').on('cocoon:after-insert', function() { $('.selectize').selectize(); });

and the form:

<div class="field"> <%= f.select :category_id, Category.all.pluck(:name, :id), {}, { class: "selectize" } %> </div>

I hope that was clear, not sure how to explain it in fewer words. Thanks in advance!


Solution

  • Imho consecutive calls of the $('.selectize').selectize(); will "break" previously selectized select-boxes. So I am assuming somehow when building your view you call that try that command for each select-box, which effectively will only keep the last one in a "good" state.

    So you will have to make sure to call it only once when creating your form. E.g. something like in your menus.js.coffee :

     $(document).on 'turbolinks:load', () ->
       $('.selectize').selectize()
    

    And then in your cocoon callback do something like the following, to only take the newly inserted html into consideration (instead of selectizing all select-boxes again):

    $('form').on 'cocoon:after-insert', (e, inserted_item) ->
      $(inserted_item).find('.selectize').selectize()