I’m not sure why the Chosen Plugin is not being called when my form partial is dynamically called.
Relative Gems –
rails, 3.1.0
cancan, 1.6.7
dynamic_form, 1.1.4
simple_form, 2.0.1
jquery-rails
Scenario –
I have a page called /index and you can add a House, Dog or Cat. The page starts out blank but has links on the side that you can click to dynamically bring up one of the forms. These forms are in a their own partials.
DogsController
def new
@dog = Dog.new
respond_to do |format|
format.js
end
end
dogs/_form.html.erb
<%= simple_form_for(@dog, :remote => true, :html => { :class => 'form-horizontal span8' }) do |f| %>
<%= render :partial => "shared/error_message", :locals => { :f => f } %>
<%= f.association :house, :prompt => "Select a House", :input_html => { :id => "house-select", :class => "span4" } %>
<%= f.button :submit, 'Done', :class => 'btn-primary span2' %>
<% end %>
PagesController
def index
@cats = current_user.cats.all
@dogs = current_user.dogs.all
respond_to do |format|
format.html
end
end
pages/index.html.erb
<li><%= link_to "Dog", new_dog_path, :remote => true %></li>
<li><%= link_to "Cat", new_cat_path, :remote => true %></li>
<div id="generate-form">
<div class="ajax-loader"></div>
</div>
dogs/new.js.erb
$("#generate-form").html("<%= escape_javascript(render(:partial => 'dogs/form', locals: { dog: @dog })) %>");
All of this code successfully brings up the chosen form on a link click.
My dog model is the same as the cat one. These are the ones with the Chosen plugin issue. Now why isn’t the Chosen plugin detected when either form is brought up?
Answer
dogs/new.js.erb
$("#generate-form").html("<%= escape_javascript(render(:partial => 'dogs/form', locals: { dog: @dog })) %>");
$('.house-select').chosen();
I don’t see any call to the chosen plugin in your code sample, but I’ve had the same issue.
The initial call to
$('.chzn-select').chosen()will apply to all DOM elements that are on the page at the time, but not to elements that get added later.To add the plugin to the new
.house-selectelements that are inserted via AJAX, add this to the end of dogs/new.js.erb:$('#generate-form .house-select').chosen();It’s worth noting that you can safely run the jQuery .chosen() function on a select box more than once. It adds its own css classes to track which ones have had chosen applied and will gracefully ignore them on consecutive runs.