我有一个用于客户端的collection_select,可以选择使用模式添加新客户端。我希望select2 collection_select使用新客户端进行更新,并将值设置为新添加的客户端。
在父窗体中,我有:
<%= f.collection_select :client_id, @clients, :id, :name, { label: 'Client', prompt: true, autofocus: true, required_flag: true }, { class: 'form-control js-example-basic-single', autofocus: true } %>
<div class='form-group'>
<%= link_to 'Add a New Client', '#new_client_modal', 'data-toggle' => 'modal' %>
</div>在客户端控制器中,我有:
@clients = Client.where(account_id: current_account.id)
format.html { redirect_to client_url(@client) }
format.js { render action: 'show', status: :created, location: @client }在show.js.erb中,我有:
$('#new_client_modal').modal_success();
$(".js-example-basic-single").val("<%=j @client.id.to_s %>").trigger("change");
<% flash.each do |type, message| %>
$('#flash_messages').html("<%=j render 'layouts/error' %>")
<% end %>我们的想法是关闭add client模式,然后用新的@clients‘选项更新select2集合select。希望用@clients更新集合select并将值设置为@client。
请注意,我使用的是select2 4.0版。
发布于 2015-06-01 10:08:23
可能是一种更好的方法,但这是我最终得到的结果:
$(".js-example-basic-client").select2({
data: [{ id: "<%=j @client.id.to_s %>", text: "<%=j @client.name %>" }],
theme: "bootstrap"
});
$(".js-example-basic-client").val("<%=j @client.id.to_s %>").trigger("change");data命令将最近添加的客户端添加到下拉列表中,但位于底部。理想情况下,我必须删除下拉选项,然后添加完整的客户端列表。现在,由于将选定的值设置为最近添加的客户端,因此可以使用此方法。
https://stackoverflow.com/questions/30550910
复制相似问题