jquery - Rails 4 Dynamic Collection_Select -
this seems pretty popular question here, though have yet find tutorial or thread works me. have 2 dropdown menus in form, team type , user role, user role dependent on team type. options team type stored in model array, since there 5 choices (artist, venue, promoter, independent, other). source selections user role model well, proper array selected depending on team type. possible, or need create models each team type , pass id join table select proper user role? thank you.
model
class waitinglist < activerecord::base companies = ['—select—', 'artist team', 'venue team', 'promoter', 'independent', 'other'] artist_team = ['-select-', 'artist', 'manager', 'tour manager', 'production manager', 'agent', 'other'] venue_team = ['-select-', 'artist liason', 'stage manager', 'production manager', 'owner', 'other'] promoter = ['-select', 'talent buyer', 'other'] independent = ['-select', 'agent', 'photo/video', 'tour manager', 'manager', 'other'] end
form
<div class="form--col"> <label>team type</label> <div class="dropdown-wrapper"> <%= f.collection_select :company_type, waitinglist::companies, :to_s, :to_s, {:include_blank => false}, {:class => "form--dropdown -team_type"} %> </div> </div> <div class="form--col -inactive"> <label>main role</label> <div class="dropdown-wrapper"> <%= f.collection_select :user_type, waitinglist::users, :to_s, :to_s, {:include_blank => false}, {:class => "form--dropdown", :disabled => "disabled"} %> </div> </div>
i think should ajax request adding javascript onchange
function. add new method handle ajax request
form
<div class="form--col"> <label>team type</label> <div class="dropdown-wrapper"> <%= f.collection_select :company_type, waitinglist::companies, :to_s, :to_s, {include_blank: false}, {onchange: "getroles();", class: "form--dropdown -team_type"} %> </div> </div> <div class="form--col -inactive"> <label>main role</label> <div class="dropdown-wrapper"> <%= f.collection_select :user_type, {}, {prompt: 'main role'} {:class => "form--dropdown", :disabled => "disabled"} %> </div> </div>
javascript file
function getroles() { var currentrole = $('#company_type :selected').val(); $.ajax({ url: '/waiting_lists/'+ currentrole +'/get_role', datatype: "json", success: function(data) { $('#user_type').html(''); (i in roles) { if (roles[i] != undefined) { $('#user_type').append("<option value=\""+roles[i]+"\">"+roles[i]+"</option>"); } } } }); }
controller
i added route waiting_lists controller
def get_role() if params[:role] case params[:role] when 'artist team' roles = waitinglist::artist_team when 'venue team' roles = waitinglist::venue_team when 'promoter' roles = waitinglist::promoter when 'independent' roles = waitinglist::independent when 'others' roles = [] end render json: {roles: roles} end end
routes
added route waiting_lists controller
resources(:waiting_lists) collection get(':role/get_role', action: :get_role) end end
hope helpful.
Comments
Post a Comment