简体   繁体   中英

Rails generate options with classes based on parent for jQuery conditional hiding

I have a couple of forms that have select boxes that I would like to conditionally hide the options based on previous options selected. For example:

On the sign up page I have 2 select boxes, agency and branch. The agency select is generated using

<%= f.select(:agency_id, options_from_collection_for_select(Agency.all, :id, :name), prompt: 'Select your Agency') %>

and the branch one:

<%= f.select(:branch_id, options_from_collection_for_select(Branch.all, :id, :name), prompt: 'Select your Branch') %>

Models:

Branch belongs_to :agency
Agency has_many :branches

I want to only show branches based on the agency selected. I'm not a jQuery whizz but I'm sure if I can add classes to the branch options based on their agency then I can use some basic javascript to achieve this.

Any ideas?

Thanks

You can do this way

function getBranches(agency_id) {  
  jQuery.ajax({
    url: "/get_branches",
    type: "GET",
    data: {"agency_id" : agency_id},
    dataType: "html"
    success: function(data) {
      jQuery("#branches").html(data);
    }
  });
 }

Now in controller

def get_branches
  @branches = Agency.find(params[:agency_id]).branches
  render :partial => 'branches', :locals => {:f => f, :branches => @branches}
end

Now in view your view

<%= f.select :agency_id, options_from_collection_for_select(Agency.all, :id, :name), prompt: 'Select your Agency', :onchange => "getBranches(this.value)" %>
<div id="branches">
  <%= render :partial => 'branches', :locals => {:f => f, :branches => @branches} %>
</div>

The partial view _branches.html.erb

<%=  f.select :branch_id, options_from_collection_for_select(branches, "id", "name"), :prompt => "Select a Branch of the Agency" %>

In routes

match "/get_branches" => "<controller_name>#get_branches"

controller_name is the name of the controller where you define get_branches

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM