【问题标题】:How do I change a dropdown menu to radio buttons?如何将下拉菜单更改为单选按钮?
【发布时间】:2013-11-24 13:18:45
【问题描述】:

我有一个带有选项列表的下拉菜单:

select_tag(:"answers[#{question.question_no}]", options_for_select( [['Agree Strongly', 7], ['Agree Mostly', 6], ['Agree Somewhat', 5], ['Neither Agree Nor Disagree', 4], ['Disagree Somewhat', 3], ['Disagree Mostly', 2], ['Disagree Strongly', 1]] ))

我希望它显示七个单选按钮。这怎么可能。如果有的话?

【问题讨论】:

  • 未来,当您提出请求代码的问题时,Stack Overflow 期望您显示您搜索过的位置、这些结果的哪些问题以及您自己尝试过的任何内容表明你已经努力自己解决问题。如果不这样做,问题就会偏离主题并被关闭。

标签: ruby-on-rails ruby button radio


【解决方案1】:

如果您想获得多个单选按钮,只需使用 rails 表单助手:radio_button_tag

radio_button_tag(:"answers[#{question.question_no}]", '7')
label_tag(:answer_agree_strongly, "Agree Strongly")
radio_button_tag(:"answers[#{question.question_no}]", '6')
label_tag(:answer_agree_mostly, "Agree Mostly")
...

所有同名的单选按钮将被分组,用户只能选择一个。

附:可能您想遍历您的选项数组以使代码更清晰。

【讨论】:

    【解决方案2】:
       <%- [['Agree Strongly', 7],
           ['Agree Mostly', 6],
           ['Agree Somewhat', 5],
           ['Neither Agree Nor   Disagree', 4],
           ['Disagree Somewhat', 3],
           ['Disagree Mostly', 2],
           ['Disagree Strongly', 1]].each do |button| %>
          <%= radio_button_tag :name, button.first, :value => button.last %>
        <% end %>
    

    最好列出控制器

    ...控制器

      def some_action
      @choices = [['Agree Strongly', 7],
               ['Agree Mostly', 6],
               ['Agree Somewhat', 5],
               ['Neither Agree Nor   Disagree', 4],
               ['Disagree Somewhat', 3],
               ['Disagree Mostly', 2],
               ['Disagree Strongly', 1]]
      end
    

    ...观看次数

       <% @choices.each do |button| %>
         <%= radio_button_tag :name, button.first, :value => button.last %>
       <% end %>
    

    【讨论】:

      【解决方案3】:

      当然可以:)

      <% ['Agree Strongly', ..., 'Disagree Strongly'].each do |option| %>
        <%= radio_button_tag(:name, option) %>
        <%= label_tag("name_#{option}") %>
      <% end %>
      

      【讨论】:

        猜你喜欢
        • 2017-08-26
        • 2015-08-06
        • 2014-05-27
        • 1970-01-01
        • 2018-09-16
        • 2014-12-30
        • 2017-02-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多