【问题标题】:Rails select tag selected valueRails 选择标记选定值
【发布时间】:2013-03-06 16:33:20
【问题描述】:

我的标签:

<%= select_tag(:option, options_for_select([['All', 1], ['Co', 2], ['Bought', 3], ['View', 4], ['Top API', 5], :selected => :option ])) %>

如何将选定的值设置为选择的选项。例如,如果我选择['Bought', 3] 并提交,则选择['All', 1] 选项。提交表单后如何显示选定的值。

【问题讨论】:

  • 如果你在浏览器中选择['Bought', 3]然后提交,你在哪里看到['All', 1]被选中了?您能显示表单的其余部分以及与表单操作相关的控制器代码吗?
  • 选项在错误的位置关闭(]),因此浏览器将:selected =&gt; :option 视为一个选项。修复问题后,您可以刷新浏览器,选中的选项将保持选中状态。

标签: ruby-on-rails ruby-on-rails-3 ruby-on-rails-3.1


【解决方案1】:

你做的一切都是对的,只需关闭:selected =&gt; :option之前的选项:selected =&gt; :option

而不是...], selected: :option ])),改为...]], selected: :option ))

所以,你的代码应该是:

<%= select_tag(:option, options_for_select([['All', 1], ['Co', 2], ['Bought', 3], ['View', 4], ['Top API', 5]], selected: :option )) %>

【讨论】:

  • 如何指定选择哪个值?
【解决方案2】:

试试这个:

<%= select_tag(:option, options_for_select([['All', 1], ['Co', 2], ['Bought', 3], ['View', 4], ['Top API', 5]], :selected => params[:option])) %>

这在 Rails 4.2 中完美运行

【讨论】:

    【解决方案3】:

    如果你想在标签中添加一个类:

    <%= select_tag(:option, options_for_select([["Option 1",1],["Option 2",2],["Option 3",3]], params[:option] ), class:"select") %>
    

    在 Rails 5 中工作。

    【讨论】:

      猜你喜欢
      • 2014-12-12
      • 2012-09-23
      • 2016-11-22
      • 1970-01-01
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多