javascript - How to Update a Select2 4.0 Collection Select Options -


i have collection_select clients option add new client using modal. select2 collection_select update new client , set value newly added client.

inside parent form, have:

<%= 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 new client', '#new_client_modal', 'data-toggle' => 'modal' %> </div> 

in clients controller have:

@clients = client.where(account_id: current_account.id) format.html { redirect_to client_url(@client) } format.js   { render action: 'show', status: :created, location: @client } 

in show.js.erb have:

$('#new_client_modal').modal_success(); $(".js-example-basic-single").val("<%=j @client.id.to_s %>").trigger("change"); <% flash.each |type, message| %>   $('#flash_messages').html("<%=j render 'layouts/error' %>") <% end %> 

the thought close add client modal , update select2 collection select new @clients `options. hope update collection select @clients , set value @client.

note using select2 version 4.0.

probably better way ended with:

$(".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"); 

the data command added added client dropdown, @ bottom. ideally have remove dropdown options, , add complete list of clients. works since setting selected value added client.


Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -