在Rails中使用Ajax动态更新选择标签 [英] Update select tag dynamically with ajax in rails

查看:92
本文介绍了在Rails中使用Ajax动态更新选择标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在视图中有两个下拉菜单,并且尝试根据第一个下拉菜单中的选定值来更新第二个下拉菜单选项.

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.

我知道有关此主题的Railscast,但是我不想使用分组的集合.这样做的原因主要是用户可以从一个下拉菜单中进行选择,也可以从另一个下拉菜单中进行选择,并相应地过滤结果,从第一个下拉菜单中选择一个值时,第二个过滤其选项.

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.

我的问题是,如何从js.erb文件中重新填充select_tag选项?

My question is, how can I re-populate the select_tag options from a js.erb file?

表格

  <%= 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')

控制器

@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.

推荐答案

添加escape_javascript以逃避承运人退货,即由options_from_collection_for_select生成的单引号和双引号.

Add escape_javascript to escape carrier returns, single and double quotes that get generated by options_from_collection_for_select.

除了将呼叫添加到escape_javascript之外,我没有看到其他任何问题.请在您的 js.erb 中尝试以下操作:

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 %>

这篇关于在Rails中使用Ajax动态更新选择标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆