当选择元素更改时,Rails更新表单的内容

时间:2011-03-16 20:17:45

标签: javascript ruby-on-rails ujs

我有一个带有选择框和三个文本输入框的表单。当选择框中的选项发生更改时,我希望使用与所选选项对应的值更新三个文本输入框。值是存储在服务器上的模型对象。

我正在使用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

因此,每当“地区”发生变化时,我希望填充城市/州/国家/地区字段。请注意,区域也是表单本身的一部分。

1 个答案:

答案 0 :(得分: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
    }
  });
});

在Rails端,在LocationsController#show:

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

这大致是如何运作的。将你所拥有的控制器/型号名称替换为我所组成的名称。

相关问题