I figured out, that throughout the generation of the nested form divs, i don't know how to get a default value there.
Within the normal form, it looks like following
<%= f.hidden_field :toolkeeper, :id => "toolkeeper_value" %>
<%= f.select :toolkeeper, options_from_collection_for_select(@people, :id, :name), :include_blank => true, :selected => '25' %>
and the corresponing JS:
$ ->
$("#practice_toolkeeper")
.select2({
allowClear: true,
placeholder: 'Select an item'
})
.select2('val',$("#toolkeeper_value").val())
but within the generation of the nested forms, the hidden_field #ID which I use to get the existing value for the selector changes like :
select#practice_uebung_maps_attributes_1_role_id
select#practice_uebung_maps_attributes_2_role_id
...
what is the correct way to write a JS-Script, which initializes the .select2() and also takes the hidden_field value?
Ok i've finally figured it out with some help of my friends:
i've added a function, to create select2 forms:
function build_select2_role(counter){
$("#practice_uebung_maps_attributes_"+counter+"_role_id").select2({
allowClear: true,
placeholder: 'Rolle'
}).select2('val',$("#role_id_"+counter).val())
};
and in the fields_for section, i only call this function (filled by a local variable):
<% @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 %>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.