【问题标题】:rails form - 2 fields with same id in a form - how to disable second field when first field is selectedrails form - 表单中具有相同 id 的 2 个字段 - 选择第一个字段时如何禁用第二个字段
【发布时间】:2011-06-02 10:52:00
【问题描述】:

我的 Rails 中有以下代码:

<label>Fruit: </label>  <%= f.select(:IST_FRUIT, [['Apple', 'Apple'],
                          ['Orange', 'Orange'],
                          ['Kiwi', 'Kiwi'],
                          ['Other', 'Other']
                          ],{ :prompt => "Please select"},{:onchange => "if (this.value == 'Other') 
                                                                         {document.getElementById('otherTissue').style.display = 'block';
                                                                         } "}
                          ) %>

<span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :IST_FRUIT, :size => 10  %></span>

用户可以从列表框中选择水果,但如果用户选择“其他”,则会显示一个文本字段,允许用户输入他的值。

问题是当用户选择一个水果并保存表单时,表格中的水果字段为空白,原因是表单正在保存在 id 为 'IST_FRUIT' 的 span 中找到的第二个字段 'IST_FRUIT'。

如果有人能告诉我如何在未选择“其他”时禁用第二个字段并在从下拉列表中选择“其他”时启用它,我将不胜感激。

非常感谢您提供的任何建议。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    首先,请注意,rails 帖子基于字段的名称,而不是 ID。

    在您的情况下,您应该使用virtual attribute 来存储潜在的other fruit 值。

    您的模型可能如下所示:

    attr_accessor :other_fruit
    
    before_save :check_fruits
    
    def check_fruits
      #if other_fruit is not nil, it means that you want to store it's value in you IST_FRUIT column 
      #BTW, why these capital letters?
      IST_FRUIT = other_fruit unless other_fruit.nil?
    end
    

    你的表格是:

    <span id="otherFruit" style="display:none;"> If other, please state: <%= f.text_field :other_fruit, :size => 10  %></span>
    

    【讨论】:

    • 您好,非常感谢您的建议。我将'def check_fruits'函数放在我的水果模型中,现在出现以下代码行错误'IST_FRUIT = other_fruit除非other_fruit.nil? - 它说动态常量分配错误'
    • 你的table叫什么名字?这是IST_FRUIT 还是更可能是ist_fruits?
    • 知道了 - 改变 'IST_FRUIT = other_fruit 除非 other_fruit.nil? ' 到 'self[:IST_FRUIT] = other_fruit 除非 other_fruit.blank?
    【解决方案2】:

    我还有一个建议。不要禁用 HTML 输入(顺便说一下,ID 在 HTML 文档中必须是唯一的)只需在模型中创建另一个属性,例如将其命名为“other_fruit”,如果“fruit”设置为“,则使用此值”其他'或为空。例如,你可以这样写:

    class TheModel
      attr :other_fruit
    
      # Overwritten accessor for the fruit attribute.
      # Returns the values of :other_fruit if :fruit is blank.
      #
      def fruit
        if self[:fruit].blank?
          other_fruit
        else
          self[:fruit]
        end
      end
    end
    

    现在是 HTML 部分。在您的 JavaScript 中,您将“显示”设置为阻止,但当用户选择另一个选项时,您不会重置它。

    如果你想阻止字段被发送到服务器,你应该设置'disabled'属性。设置“样式”只会将控件隐藏在用户的视线之外。

    【讨论】:

      猜你喜欢
      • 2017-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-09
      • 2017-11-16
      • 1970-01-01
      • 2020-08-08
      相关资源
      最近更新 更多