簡體   English   中英

使動態生成的選擇框值在表單參數中可用

[英]Make dynamically generated select box value available in form params

我覺得應該有一個非常簡單的解決方案...但是我找不到它。

我正在使用jquery在依賴於另一個選擇框的窗體內動態生成一個選擇框。

在我看來,表單代碼的摘錄:

form_for @unit do |f|

    <td> f.collection_select :shop_id, @shops, :id, :name </td>     # this is the first select box

    <td id="options"></td>     # this is the id tag that jquery finds and replaces with the second select box, depending on the value of the first select box

在我的application.js中,我具有捕獲第一個選擇框的值並將其發送到我的控制器的功能:

jQuery(function($) {

    // when the #shop field changes
    $("#unit_shop_id").change(function() {

    var shop_id
    shop_id = $('select#unit_shop_id :selected').val();

    // make a GET call and replace the content
    jQuery.get('/units/options/' + shop_id )
    return false;
    });
});

然后在我的units_controller中,根據shop_id設置第二個選擇框的選項,並調用js.erb文件:

def options     # note params[:id] is the shop_id specified by the first select box

    if params[:id] == 0 
        @options = ["Yes", No", "Maybe"]
            elsif params[:id] == 1
                @options = ["Yes", Maybe"]
            else
                @options = ["Yes"]
            end

    respond_to do |format|
        format.js {}
    end
end

我的options.js.erb文件動態顯示第二個選擇框:

$("#options").html( "<%= escape_javascript(select("product_id", @options)) %>" ); 

所有這一切都完美。 將顯示我的表單,當我在第一個選擇框中選擇一個值時,它將確定第二個選擇框中可用的選項。

我正在努力的是如何將在第二個選擇框中選擇的值添加到表單參數中。

生成的形式參數為:

    "unit"=>{"shop_id"=>"x"}    (i.e. only the first select box)

我想生成包含第二個選擇框的表單參數,這些第二個選擇框由jquery動態生成,即:

    "unit"=>{"shop_id"=>"x", "product_id=>"y"}

知道如何做到這一點嗎? 我嘗試使用product_id形式的hidden_​​field,但似乎無法成功引用product_id。

查看select的文檔,看起來select的定義如下:

select(object, method, choices = nil, options = {}, html_options = {}, &block)

我相信同時使用對象unit )和方法product_id )應該可以為您提供所需的行為。

$("#options").html( "<%= escape_javascript(select("unit", "product_id", @options)) %>" );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM