Question

In my application I have two models: Product and Color. Product has many Colors, and I am using the nested_form gem to add Colors dynamically to Product in the Product form. This is my view:

# app/views/products/_form.html.erb
<%= nested_form_for @product do |f| %>

  <%= f.label :name %>
  <%= f.select(:name, options_for_select(@product_names), { include_blank: true }) %>

  <%= f.fields_for :colors do |c| %>
    <%= render "color_fields", :f => c %>
    <%= c.link_to_remove "Remove this color" %>
  <% end %>

  <%= f.link_to_add("Add a color", :colors) %></p>

<% end %>

And:

# app/views/products/_color_fields.html.erb
<%= f.label :color %>
<%= f.select(:color, options_for_select(@color_options, :selected => @color_options.first), {}, { :class => 'color_select' }) %>

Besides, I use the jquery-simplecolorpicker-rails gem to transform the color select form in a color picker.

The select form is transformed into the color picker with the following lines:

# app/assets/javascripts/products.js.coffee
$ ->
  $('select[class="color_select"]').simplecolorpicker({theme: 'regularfont'})

In my controller I build two initial color elements: 2.times { @product.colors.build }. The select forms to these two colors are correctly transformed into color pickers by my javascript lines. But when I click the link "Add a color", the new color select form is not displayed as a color picker, but as a normal select.

How can I trigger the $('select[class="color_select"]').simplecolorpicker({theme: 'regularfont'}) call so every time a new color select is created, it is displayed with as a color picker?

Was it helpful?

Solution

Reading properly the nested_form documentation, I found the answer for this question.

When you click "Add a color", the event nested:fieldAdded and nested:fieldAdded:colors will be triggered, while nested:fieldRemoved and nested:fieldRemoved:colors will be triggered if you click "Remove this color".

So, the coffeescript to solve this problem is:

$(document).on "nested:fieldAdded", (event) ->
  $('select[class="t_shirt-color_select"]').simplecolorpicker({theme: 'regularfont'})

And it's corresponding JavaScript:

$(document).on('nested:fieldAdded', function(event){
  $('select[class="t_shirt-color_select"]').simplecolorpicker({theme: 'regularfont'})
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top