【发布时间】:2015-09-28 14:16:14
【问题描述】:
所以我有选择标签和嵌入的选项标签。我在这里得到了帮助,Jquery Filter next select group based on selection of previous select group, 关于如何根据上一个选择组的选择过滤下一个选择组。
在更深层有很多选项,所以我想知道如何使用 ajax 请求来做到这一点。我希望通过 ajax 填充 layer2(和更深层)。
下面是一些玩具 html,同样来自这里,Jquery Filter next select group based on selection of previous select group, 演示如何使用我得到帮助的 jquery 来影响具有前一层的更深的多选框。
<select id="layer1" multiple="multiple">
<option data-id="3">Chocolate</option>
<option data-id="5">Cookie</option>
</select>
<select id="layer2" data-depends-on="layer1" multiple="multiple">
<option data-parent="3" data-id="6">Milk Chocolate</option>
<option data-parent="5" data-id="7">Sprinkled Cookie</option>
<option data-parent="5" data-id="8">Iced Cookie</option>
</select>
<script>
$("select").each(function(){
// cache all options
$(this).data('options', $('option', this));
}).on('change', function(e){
var current = this, selected = [];
// find all selected for the current select and
// store them in a local variable
$('option:selected', current).each(function(){
selected.push($(this).data('id'));
});
// find all selects that depend on this one.
$("select").filter(function(){
return $(this).data('depends-on') === current.id;
}).each(function(){
// search our cached options and filter them
// by the selected option(s). Store them in
// a local variable.
var children = $(this).data('options').filter(function(){
return selected.indexOf($(this).data('parent')) > -1;
});
// empty and repopulate the select with the
// filtered results. Also, trigger the next
// select so the effect cascades.
$(this).empty().append(children).trigger('change');
});
}).trigger('change'); // trigger change so it filters
// on page load.
</script>
这里有一些 Rails 代码和相应的视图,让您了解我是如何使用 Rails 进行操作的。 Rails 代码
def new
@one = CategoryLevelOne.all.map { |c| [c.id, c.name] }
@two = CategoryLevelTwo.all.map { |c| [c.id, c.name] }
end
对应视图
<%=form_tag('/companies', method: :post)%>
<select name="category_id[]" id="layer1" multiple="multiple" size="20">
<%= render 'companies/list/category_one' %>
</select>
<select name="category_id2[]" data-depends-on="layer1" id="layer2" multiple="multiple" size="20">
<%= render 'companies/list/category_two' %>
</select>
<%= submit_tag%>
//the same jquery script is used as in the above code
公司/列表/_category_one.html.erb
<% @one.each do |c| %>
<option data-id=<%=c[0]%> value=<%=c[1]%>><%=c[1]%></option>
<% end %>
我想做一个 ajax 请求,它对控制器操作执行 GET 请求,获取一个对象,然后使用该对象,在指定的选择标签内创建/更新一堆选项标签。
所以我想它看起来像这样
ajax 请求触发某个控制器动作的某个 GET 请求 在该控制器动作中,它获取某个对象数组,并以 json 的形式返回它。 采用该数组并能够执行类似于
的操作的 javascript<% @one.each do |c| %>
<option data-id=<%=c[0]%> style="color:<%=c[2]%>" value=<%=c[1]%>><%=c[1]%></option>
<% end %>
对于特定的选择标签。
【问题讨论】:
标签: javascript jquery html ruby-on-rails ajax