[英]how to pre-populate the form (ajax way) on performing a selection from a dropdown list inside it, Ruby on Rails?
這是我目前的_form.html.erb部分,但我希望根據我做出的第一個(區域)下拉選擇來更新其元素:
<%= form_for(@setting) do |f| %>
<div class="form">
<div class="fieldBlock">
<%= f.label :region%>
<%= f.select :region_id, options_from_collection_for_select(Region.all, 'id', 'region_code'),
:onChange => remote_function(:update => ":mobile, :telephone", :method => "get", :url => { :controller => :Settings, :action => :form_update, :id => :region_id}) %>
</div>
<div class="fieldBlock">
<%= f.label :city_id, "City" %>
<%= f.select :city_id, options_from_collection_for_select(City.all, 'id', 'name'), :prompt => 'select a city' %>
</div>
<div class="fieldBlock">
<%= f.label :mobile, "Mobile" %> <%= f.text_field :mobile%></div>
<div class="fieldBlock">
<%= f.label :telephone, "Telephone No" %> <%= f.text_field :telephone %></div>
<div class="fieldBlock">
<% f.submit "Update Contact" %>
At present this is the controller method that helps in prepopulating:
def index
setting = Setting.find_by_user_id(current_user.id)
if setting.blank?
@setting = City.first.dup
else
@setting = setting
end
結束
在選擇區域下拉列表值時如何以Ajax方式更新表單?
現在,這是我的form_update動作:
def form_update(id)
setting = Setting.find_by_region_id(id)
respond_to do |format|
if setting.blank?
@setting = Setting.first.dup
format.json {@setting}
else
@setting = setting
format.json {@setting}
end
end
結束
我還必須使用Prototype-Rails來使remote_function起作用。 我的字段仍然沒有更新,我在這里缺少什么。
您需要使用select
標簽的OnChange
選項
這應該有助於[ 如何添加onchange事件以選擇Rails中的標簽 ]
有關使用select_tag
:onChange
選項的更好說明,請select_tag
[ http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select#51-Demo-select-onchange-invoke-an-ajax- ]
編輯:
說明:當您選擇下拉菜單的任何選項時,將執行OnChange
提供的操作。 現在,您可以對服務器進行ajax調用,以獲取要用來更新字段的值。 為此,您需要remote_function
(如下所述)。
考慮您的示例,以下代碼段應該有效
<%= form_for(@setting) do |f| %>
<div class="form">
<div class="fieldBlock">
<%= f.label :region%>
<%= f.select :region_id, options_from_collection_for_select(Region.all, 'id', 'region_code'),
:onchange => remote_function( ... ... ...) %>
</div>
<% end %>
上面我僅顯示了表單的下拉部分。 注意這里的:onchange
選項。 它應該包含一個remote_function
,如下所示
:onchange => remote_function(:update => "message_id",
:method => "put",
:with => "'item=' + value",
:url => { :controller => :orders, :action => :set_customer_id, :id => order.id}))
這里:
:update
:是HTML節點,其包含將被更新。 因此,將所有:city_id
, :mobile
和:telephone
字段放在具有唯一ID的HTML節點中,您將在此處使用該ID。
:method
:只需按照您的路線中的定義使用即可。 可能是GET。
:with
:一些額外的屬性來提供請求。
:url
:您必須請求的URL。
如果仍然不能解決問題,請分享您的嘗試方式。 可能是一個小的解決方案可以解決問題。
如果您將Rails與jquery一起使用,則可以嘗試以下操作
http://samuelmullen.com/2011/02/dynamic-dropdowns-with-rails-jquery-and-ajax/
雖然我自己沒有嘗試過,但是聽起來很有趣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.