2012-02-17 46 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