【问题标题】:Rails Updating Contents of a Form When a Select Element ChangesRails 在选择元素更改时更新表单的内容
【发布时间】:2011-03-16 20:17:44
【问题描述】:

我有一个带有一个选择框和三个文本输入框的表单。 When the option in the select box changes, I want to update the three text input boxes with values corresponding to the selected option.这些值是存储在服务器上的模型对象。

我正在使用 Rails 3 并试图保持不引人注目,但我找不到一个干净的方法来做到这一点。我想出了几个可怕的、混乱的解决方案,但还没有一个干净的解决方案。将这一切联系在一起的好方法是什么?特别是,我遇到了从服务器请求模型对象的选择元素的问题。

这是生成表单的视图:

= 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

所以我希望在“地区”更改时填充城市/州/国家/地区字段。请注意,区域也是表单本身的一部分。

【问题讨论】:

    标签: javascript ruby-on-rails ujs


    【解决方案1】:

    在 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
    

    这大概就是它的工作原理。用你拥有的任何控制器/模型名称替换我编造的名称。

    【讨论】:

    • 谢谢!这使我朝着解决问题的正确方向前进。我试图通过让动作渲染 RJS 来过度杀死它,但是处理 javascript 变得更加困难:)
    • 没问题,很高兴我能帮上忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2011-04-14
    相关资源
    最近更新 更多