【问题标题】:Issues with dropdown select_tag placeholder with prompt带有提示的下拉 select_tag 占位符的问题
【发布时间】:2016-11-26 07:31:48
【问题描述】:

我在使用 rails select_tag 帮助器在下拉选择表单中设置占位符时遇到问题。使用提示选项存在占位符,但此方法会在下拉列表中产生无法单击的死重复值:

这是我的代码:

@posts = Post.all
@categories = Post.uniq.pluck(:category)
@prompt = "Select Category"

if params[:category]
   @posts = Post.where(category: params[:category])
   @prompt = params[:category]
end

<%= form_tag(h_path, :method => "get") do %>
   <%= select_tag 'category', options_for_select(@categories), {onchange: "this.form.submit();", prompt: @prompt} %>
<% end %>

任何关于使占位符值在这种情况下很好地工作的想法或建议将不胜感激。我的意思是类似于此页面上的类别下拉选择示例: http://www.joeabercrombie.com/category/audiobooks/

【问题讨论】:

    标签: ruby-on-rails html-select


    【解决方案1】:

    您需要的不是提示。提示是向用户显示此下拉列表含义的消息。从您的 Audible 页面示例中,在类别选择下拉列表中“选择类别”是提示。

    您需要设置一个选定的选项。如果设置了params[:category],您希望从现有的选择选项中选择一个选项。在这种情况下,重命名变量并将“待选择”选项传递给 options_for_selectselect_tag 助手。

    @posts = Post.all
    @categories = Post.uniq.pluck(:category)
    @prompt = "Select Category"
    
    if params[:category]
       @posts = Post.where(category: params[:category])
       @selected_category = params[:category]
    end
    
    <%= form_tag(h_path, :method => "get") do %>
       <%= select_tag 'category', options_for_select(@categories, @selected_category), {onchange: "this.form.submit();", prompt: @prompt} %>
    <% end %>
    

    参考:select_tag (ActionView::Helpers::FormTagHelper) - APIdock

    【讨论】:

      【解决方案2】:

      您可以直接将params[:category]作为已选择的值传递给select_tag

      并且还将uniq移动到末尾line:2

      @posts = Post.all
      @categories = Post.pluck(:category).uniq
      
      if params[:category]
        @posts = Post.where(category: params[:category])
      end
      
      <%= form_tag(h_path, method: :get) do %>
         <%= select_tag :category, options_for_select(@categories, params[:category]), onchange: "this.form.submit();", prompt: "Select Category" %>
      <% end %>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-17
        • 2021-08-18
        • 2014-10-03
        相关资源
        最近更新 更多