2012-08-23 29 views
1

我正在嘗試製作一個以3選擇下拉菜單開始的表單。漂亮的標準 -在Rails中創建3部分的AJAX選擇表單

The selection of drop down 1 populates the options in drop down 2

然後,

The selection of drop down 2 populates the options in drop down 3

我按照sled的回答到這裏simular問題,https://stackoverflow.com/a/6864321/766817但我想不出(用他的例子) ,如何在混合中添加第三個元素。以下是我迄今爲止...

_form.html.erb

<%= select_tag :first_select, 
("<option>Product Grade...</option>" + options_from_collection_for_select(@product_grades, "id", "product_grade")).html_safe, 
    :'data-remote' => 'true', 
    :'data-url' => url_for(:controller => 'product_grades', :action => 'getdata'), 
    :'data-type' => 'json' 
%> 

<%= select_tag :second_select, 
    :'data-remote' => 'true', 
    :'data-url' => url_for(:controller => 'vendors', :action => 'getdata'), 
    :'data-type' => 'json' 
%> 

<%= select_tag :third_select %> 

的application.js

$('#first_select').live('ajax:success', function(evt, data, status, xhr) { 

    var selectbox2 = $('#second_select'); 

    selectbox2.empty(); 

    $.each(data, function(index, value) { 
    var opt = $('<option/>'); 

    opt.attr('value', value[0]); 
    opt.text(value[1]); 
    opt.appendTo(selectbox2); 
    }); 
}); 


$('#second_select').live('ajax:success', function(evt, data, status, xhr) { 

    var selectbox3 = $('#third_select'); 

    selectbox3.empty(); 

    $.each(data, function(index, value) { 
    var opt = $('<option/>'); 
    opt.attr('value', value[0]); 
    opt.text(value[1]); 
    opt.appendTo(selectbox3); 
    }); 
}); 

最後,我有兩個getdata行動ProductGradesControllerVendorsController

ProductGradesController

def getdata 
    @data_from_select1 = params[:first_select] 
    @data_for_select2 = Vendor.where(:product_grade_id => @data_from_select1).all 
    render :json => @data_for_select2.map{|c| [c.id, c.vendor_name]} 
end 

VendorsController

def getdata 
    @data_from_select2 = params[:second_select] 
    @data_for_select3 = ItemCode.where(:vendor_id => @data_from_select2).all 
    render :json => @data_for_select3.map{|a| [a.id, a.item_code]} 
end 

目前,前兩步工作,但是第三步產生一個選擇框,但是當你選擇前兩個選項沒有數據填充腳步。

我很新的jQuery AJAX查詢等,所以我相信我做錯了那裏,但任何想法?謝謝!!

回答

0

好了,任何人誰在將來遇到類似的問題,其實我最終採取了不同的路線......

這些下拉菜單會處理的數據量也不會很多,所以我實際上通過一個名爲jQuery Chained(https://github.com/tuupola/jquery_chained)的jQuery插件集成了一個非AJAX'd方法。

這只是啓用/禁用下拉選項,取決於在先前的下降。 如果您的下拉菜單中填充了大量的db數據,或者您需要在下拉列表中顯示的安全層,因爲這些選項是從DOM中添加/刪除的,這不是一個很好的解決方案,這意味着人們通過查看源代碼可以很容易地看到所有的數據。

HomeOnRails博客有一篇關於如何將這個jQuery Chained插件集成到您的rails應用程序的好文章。 (http://homeonrails.blogspot.com/2012/01/rails-31-linked-dropdown-cascading.html)

享受和祝你好運!