Rails 3 + JQuery + Dynamic Combobox

时间:2012-02-17 23:22:53

标签: jquery ruby-on-rails-3

我一直在寻找其他线程,但无法得到一个例子。

我有一个“群组”组合框,当我选择一个值时,它会在选定组的值时更改组合框“类别”的值。

查看(show.html.erb)

<%= form_for(@store_classification, :url => {:action => 'add_classification'}) do |f| %>
  <fieldset>
    <legend><%= t(:newClassificationDetails) %></legend>
    <%= f.hidden_field :store_id, :value => params[:id] %>
    <div id="groups" class="fields">
      <%= f.label t(:group) %><br />
      <%= f.select :group_id,
                   options_from_collection_for_select(@groups, :id, :name),
                   :data => { :remote => true, :url => url_for(:controller => :stores,
                                                                :action => :update_categories)}%>
    </div>
    <div id="categories" class="fields">
        <%= f.label t(:category) %><br/>
        <%= f.select :category_id, options_from_collection_for_select(@categories, :id, :name) %>
    </div>
    <div class='actions'>
        <%= f.submit t(:add) %>
    </div>
  </fieldset>
<% end %>

部分(_categories.html.erb)

<div id="categories" class="fields">
        <%= f.label t(:category) %><br/>
        <%= f.select :category_id, options_from_collection_for_select(@categories, :id, :name) %>
    </div>

控制器(stores_controller.rb)

def show
    @store_classification = StoreClassification.new    
    @groups = Group.all
    @categories = Category.all
  end

  def update_categories
    category = Category.find(:all,
                             :conditions => ['group_id = ?',params[:selected]])
    render :partial => :categories
  end

Javascript(application.js)

$(document).ready(function(){
    $("#groups").change(function() {
        $.ajax({url: '<%= url_for :action => :update_categories, :id => @group_id %>',
        data: 'selected=' + this.value,
        dataType: 'script'})
    });
});

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

不知道你可能应该发布由它生成的html的rails东西,任何方式将change事件处理程序附加到groups组合

$("#groupCombo").change(function(e){

  //make the ajax call to get the categories

  $.ajax({
     url:"url",
     type:"get",
     dataType:"json", //the type of response you are expecting from the server
     success:function(data){
        $("#categoryCombo").empty(); //clear the categories combo

        //iterate over the result sent by the server and populate the category combo e.g.
         $.each(data,function(k,v){
           $("#categoryCombo").append("<option>"+v+"</option>");
         });

     },
     error:function(jxhr){
         console.log(jxhr.responseText);
     }


  });

});

DEMO