I have two dropdowns in a view, and I'm attempting to update the second dropdown options based on the selected value from the first dropdown.
I am aware of the Railscasts on this topic, but I do not want to use the grouped collections; The reasons for this are primarily that the user can select from one dropdown, or the other, and the results are filtered accordingly, the second dropdown only filters its options when a value from the first dropdown is selected.
My question is, how can I re-populate the select_tag options from a js.erb file?
form
<%= form_tag("filter", :id => "filter_form", :method => "post") do %>
<label for="company_id" class="company">Company</label><%= select_tag(:company_id, options_from_collection_for_select(Company.all.order(:name), :id, :name), :prompt => "All Companies") %>
<label for="product_id" class="product">Product</label><%= select_tag(:product_id, options_from_collection_for_select(Product.all.order(:name), :id, :name), :prompt => "All Products") %>
<% end %>
js.coffee
$('#company_id').change( ->
sendFilterForm()
)
sendFilterForm = ->
$.get($('#filter_form').attr('action'), $('#filter_form').serialize(), 'script')
controller
@filterProducts = true
@products = Product.where(company_id: params[:company_id]).order(:name)
js.erb
<% if @filterProducts %>
$('#product_id').html(<%= options_from_collection_for_select(@products, :id, :name) %>);
<% end %>
So the last part is obviously quite wrong, but that is the concept of what I am trying to do. What is the proper way to accomplish this? I am open to rework this, if needed, any help is appreciated.
Add escape_javascript
to escape carrier returns, single and double quotes that get generated by options_from_collection_for_select
.
I do not see any other problems except adding call to escape_javascript
. Please try the following in your js.erb:
<% if @filterProducts %>
$('#product_id').html("<%= escape_javascript options_from_collection_for_select(@products, :id, :name) %>");
<% end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With