我发现,在嵌套表单 div 的生成过程中,我不知道如何在那里获取默认值。
在正常形式中,它看起来如下
<%= f.hidden_field :toolkeeper, :id => "toolkeeper_value" %>
<%= f.select :toolkeeper, options_from_collection_for_select(@people, :id, :name), :include_blank => true, :selected => '25' %>
以及相应的JS:
$ ->
$("#practice_toolkeeper")
.select2({
allowClear: true,
placeholder: 'Select an item'
})
.select2('val',$("#toolkeeper_value").val())
但是在嵌套表单的生成过程中,我用来获取选择器现有值的hidden_field #ID 发生了如下变化:
select#practice_uebung_maps_attributes_1_role_id
select#practice_uebung_maps_attributes_2_role_id
...
编写 JS 脚本的正确方法是什么,它初始化 .select2() 并获取hidden_field 值?
最佳答案
好吧,在 friend 的帮助下我终于弄清楚了:
我添加了一个函数,用于创建 select2 表单:
function build_select2_role(counter){
$("#practice_uebung_maps_attributes_"+counter+"_role_id").select2({
allowClear: true,
placeholder: 'Rolle'
}).select2('val',$("#role_id_"+counter).val())
};
在 fields_for 部分,我只调用这个函数(由局部变量填充):
<% @runs = 0 %>
<td>
<%= map.hidden_field :role_id, :id => "role_id_#{@runs}" %>
<%= map.select :role_id, options_from_collection_for_select(@roles, :id, :name), :include_blank => true %></td>
<script type='text/javascript'>
build_select2_role(<%= @runs %>);
</script>
</td>
<% @runs += 1 %>
关于jquery - select2 在带有 Rails 的嵌套表单上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15728257/