2012-02-17 31 views
0

我一直在寻找其他线程,但无法得到一个例子工作。Rails 3 + JQuery + Dynamic Combobox

我有一个“组”组合框,当我选择一个值时,它将改变组合框“值”的值,当该选定组的值。

视图(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'}) 
    }); 
}); 

感谢您的帮助

回答

0

不知道铁轨的东西,你也许应该张贴它生成的HTML,任何方式附加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