Rails4 Dynamic Select Dropdown

北城余情 提交于 2019-11-29 05:15:27

You can fire jquery-ajax request. Change event in first select box will call action on controller and called method will change the value of second dropdown through ajax call. Simple example:

In your view file:

<%= select_tag 'state_id', options_for_select(State.all.order(:name), :id, :name) %>

<%= select_tag "site_id", options_for_select(Site.all.order(:name), :id, :name) %>

In JS file of that controller:

$(document).on('ready page:load', function () {
 $('#state_id').change(function(event){
      $("#site_id").attr('disabled', 'disabled')          
      $.ajax({
     type:'post',
     url:'/NameOfController/NameOfMethod',
     data:{ state_id: $(this).val() },
     dataType:"script"
   });
  event.stopImmediatePropagation();
});

});

In NameOfController.rb

def NameOfMethod
  ##no need to write anything
end

In NameOfMethod.js.erb

<% if params[:state_id].present? %>
   $("#site_id").html("<%= escape_javascript(render(partial: 'site_dropdown'))%>")
<% end %>

in _site_dropdown.html.erb file:

<% if params[:state_id].present? %>
   <%= select_tag 'site_id', options_for_select(Site.where("state_id = ?", params[:state_id])) %>
<% else %>
   <%= select_tag "site_id", options_for_select(Site.all.order(:name), :id, :name) %>

So it will change site dropdown based on selected state dropdown. You can go upto n number of level for searching. Good luck.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!