【问题标题】:Mixing radio buttons and text_field混合单选按钮和 text_field
【发布时间】:2012-08-01 07:00:09
【问题描述】:

我正在尝试将单选按钮和 text_field 组合为一个值:

= f.radio_button :system, "bacteria"
Bacteria
= f.radio_button :system, "mammalian"
Mammalian
= f.radio_button :system, "yeast"
Yeast
= f.radio_button :system, "insect"
Insect
= f.radio_button :system, "other"
Other:
= f.text_field :system, class:"input-small"

当我提交时,没有任何反应,因为即使选中了单选,参数中也给出了一个空白值(我认为它考虑了文本字段)。

我尝试给text_field取另一个名字,更新后替换了控制器中的:system值,但是看起来很脏……

你有什么更简洁的想法吗?

【问题讨论】:

    标签: ruby-on-rails forms radio-button textfield


    【解决方案1】:

    在这里你不能直接将radio_button 和text_field 混合在一起用于同一个字段。 我认为您可以定义一个额外的 radio_button 字段,该字段将被隐藏,并且当用户输入 text_field 时其值将得到更新。

    = f.radio_button :system, "bacteria"
    Bacteria
    = f.radio_button :system, "mammalian"
    Mammalian
    = f.radio_button :system, "yeast"
    Yeast
    = f.radio_button :system, "insect"
    Insect
    = f.radio_button :system, "other"
    Other:
    = f.radio_button :system, nil, :id => :hidden_radio, :style => "display:none"
    = f.text_field :free_system_input, class:"input-small", :id => :free_system_input
    

    在上面,您将在 text_field 上编写 onchange 事件,并且每当在 text_field 中输入值时,它会将隐藏的 radio_button 的值设置为 text_field_value。

    :javascript
     $("free_system_input").keyup(function(){
       $("hidden_radio").val($(this).val())
     })
    

    上面的代码只是为了给出如何处理问题的想法,并且不会像它一样工作.. :)

    【讨论】:

      【解决方案2】:

      感谢 Sandip 的帮助,我设法解决了我的问题!

      这里是视图:

      = f.radio_button :system, "bacteria"
      Bacteria
      = f.radio_button :system, "mammalian"
      Mammalian
      = f.radio_button :system, "yeast"
      Yeast
      = f.radio_button :system, "insect"
      Insect
      %br/
      = f.radio_button :system, nil, id: 'other_system_radio', 
                      checked: radio_checked?('system', f.object.system) 
      Other:
      %input.input-small#other_system_text{ value: text_input?('system', f.object.system) }
      

      我使用辅助函数来管理编辑表单(如果值与给定值不同,则填写文本字段):

      def radio_checked?(type,val)
        case type
          when 'system'
            ['bacteria', 'mammalian', 'yeast', 'insect'].include?(val) ? '' : 'checked'               
          end
        end
      
      def text_input?(type,val)
        case type
          when 'system'
            ['bacteria', 'mammalian', 'yeast', 'insect'].include?(val) ? '' : val
        end       
      end
      

      当用户关注文本字段时,还有一点 Javascript 来选择“其他”单选按钮:

      @handle_other_field = ->
        $('#other_system_text').focus( -> $('#other_system_radio').attr('checked','checked'))
        $('#other_system_text').keyup( -> $('#other_system_radio').val($(this).val()))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-10-18
        相关资源
        最近更新 更多