2011-03-16 30 views
1

我有一個帶有選擇框和三個文本輸入框的表單。當選擇框中的選項發生變化時,我想用對應於所選選項的值更新三個文本輸入框。這些值是存儲在服務器上的模型對象。更改選擇元素更改表單的內容時的軌道

我正在使用Rails 3並試圖保持事物不顯眼,但我找不到乾淨的方式來做到這一點。我想出了一些可怕的,凌亂的解決方案,但沒有乾淨。將這一切聯繫在一起的好方法是什麼?特別是,我在從服務器請求模型對象的select元素時遇到問題。

下面是生成表單視圖:

= form.select :region_id, region_options_for_select(@business_location.region), :prompt => '-- Region --' 
= form.text_field :city 
= form.text_field :state, :label => 'Province/State' 
= form.text_field :country 

所以我想只要填充「區域」是改變了城市/州/國家領域。請注意,區域也是表單本身的一部分。

回答

3

在jQuery中,這樣的事情可能工作:

$("select").live("change", function(e) { 
    e.preventDefault(); 
    $.ajax({ 
    url: "/location/" + $(this).val(), //I think, it could be something else 
    dataType: "json", 
    contentType: "application/json; charset=utf-8", 
    success: function(data) { 
     //you're returning a JSON object, so just iterate through it and bind it to 
     //the value attributes of each field 
    }, 
    error: function(xhr,exception,status) { 
     //catch any errors here 
    } 
    }); 
}); 

在軌道側,在LocationsController#顯示:

@location = Location.find(params[:id]) 
respond_to do |format| 
    format.json { render :json => @location.to_json, :status => 200 } 
end 

這大概它如何工作。用你製作的控制器/型號名替換。

+0

謝謝!激起我朝着正確的方向解決問題。我試圖通過動作渲染RJS來過度殺死它,但是然後處理javascript變得更加困難:) – u2622 2011-03-17 16:17:27

+0

沒問題,很高興我能提供幫助。 – 2011-03-17 17:29:34