简体   繁体   中英

Rails 4 - nested_form and chosen-select

I am using Ryan Bates nested_form_for: https://github.com/ryanb/nested_form . For my select statement, I am using chosen-select: http://harvesthq.github.io/chosen/ . When I click "Add Skill" I cannot get the select statement to also be class: 'chosen-select'. A new select field shows up, but it has no custom css styles.

To be clearer, the original select statements show up correctly and the ones which I add on do not have custom css styles (chosen-select).

<%= nested_form_for(@user) do |f| %>    
    <%= f.fields_for :skills do |builder| %>
            <%= builder.select :skill, data, {},  {class: 'chosen-select'} %>
            <%= builder.date_select :expdate, include_blank: true %>
            <%= builder.link_to_remove "Remove" %>
    <% end %>

        <%= f.link_to_add "Add Skill", :skills %>
<% end %>

Is there a way to make the select statements I add via the link_to_add function use the class 'chosen-select' ?

i think your problem is that the 'chosen plugin' make the changes on the element when the page is load, once the page is loaded, the new elements added are not changed, at least that you call the function again. I would treat call the function on the click event that add the new element. Something like this:

$('#add-element').on 'click', ->
  $('.chosen-select').chosen()

i am reading the documentation of nested_form, and in your case, i think is like this:

$(document).on 'nested:fieldAdded, (event)->
  $('.chosen-select').chosen()

Or, more like says the docs

$(document).on 'nested:fieldAdded, (event)->
  field = event.field
  detefield = field.find('.chosen-select')
  datefield.chosen()

I think this works!

PD: the code js is Coffescript.

PD2: I think that the cocoon gem is best for the job.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM