如何根据选中的选项显示文本数组

How can show text array according options checked?

本文关键字:选项 显示 文本 数组 何根      更新时间:2023-09-26

我正在尝试根据选中的复选框显示文本。

我有 3 种状态,所以当我选中一个或两个复选框时,将显示在没有 javascript 的情况下选择的选项。

例如:

if I check1 will show me the text active.
if I check2 will show me the text inactive.
if I check3 will show me the text inactive and active.
if I check1 and check 2 will show me the text "active","inactive".
if I check1 and check 2 will show me the text "active","removed".
if I check1 and check 2 will show me the text "removed","inactive".

只需根据选中的复选框保持文本即可。

这是控制器:

@search_state = params[:search_state]
@people = Person.all

以下是视图:

<%= form_tag(people_path,:method => "get") do %>
 #### BEGIN CHECKBOX #####
 <% if @search_state.blank? %> 
   Check1 <%= check_box_tag "search_state[]", "0" %>
   Check2 <%= check_box_tag "search_state[]", "1" %>
   Check3 <%= check_box_tag "search_state[]", "2" %>
 <% else %>
   Check1 <%= check_box_tag "search_state[]", "0", @search_state.collect(&:to_i).include?(0) %>
   Check2 <%= check_box_tag "search_state[]", "1", @search_state.collect(&:to_i).include?(1) %>
   Check3 <%= check_box_tag "search_state[]", "2", @search_state.collect(&:to_i).include?(2) %>
 <% end %>
  #### END CHECKBOX ####
 ### WANT TO SHOW A TEXT ACCORDING CHECKBOXES SELECTED ###
   <% if @search_state.to_s=="0"%>
     Active
   <% elsif @search_state.to_s=="1"%>
     Inactive
   <% elsif @search_state.to_s=="2" %>
     Removed
   <% elsif @search_state.to_s==["0","1"] %>
     Active,Inactive
   <% elsif @search_state.to_s==["0","2"] %>
     Active,Removed
   <% elsif @search_state.to_s==["1","2"] %>
     Inactive,Removed
   <% elsif @search_state.to_s==["0","1","2"] %>
     Active,Inactive,Removed
   <% end %>
   ### END WANTTO SHOW A TEXT ACCORDING CHECKBOXES SELECTED ### 
 <% end %>

以下是文件和演示:

http://runnable.com/VMkReiHVr0FbfQKN/checkbox-project-test-for-ruby-on-rails
http://runnable.com/VMkRe1xPNqFWSMtd/output

我的代码太长了,我认为这不是正确的方法。

例如,在这种情况下,我有 3 个状态,如果我有更多的状态将太长且令人困惑。

有人可以帮助我在轨道上使用 ruby 制作几行代码的复选框,请问?

我知道使用Javascript是解决方案,但是这是解决的唯一方法,请问解决方案如何?

我将非常感谢各种帮助。

我很难从您的示例中理解您的意图。 但我想你的意思是按钮 1 是"活动",按钮 2 是"非活动",按钮 3 是"已删除"。 此外,我认为您打算没有任何选择是相互排斥的......特别是,您可以同时选中"活动"和"非活动"。 您还暗示将来可能会有更多行为类似的复选框。

如果所有这些都是正确的,那么我同意,您目前的方法根本无法很好地扩展。

与其尝试根据复杂的标准选择完整的消息,我会重构它以从其组件构建消息。 沿着这些思路的东西应该让你到达那里:

  flags = []
  flags << 'Active' if @search_state.collect(&:to_i).include?(0)
  flags << 'Inactive' if @search_state.collect(&:to_i).include?(1)
  flags << 'Removed' if @search_state.collect(&:to_i).include?(2)
  puts flags.join(', ')

FWIW,如果您没有理由为所有复选框提供相同的名称和不同的值,我会给每个复选框一个不同的名称。 这将使您的许多代码变得更加简单。 大致如下:

   Check1 <%= check_box_tag "search_active", "1", @search_active == 1) %> Active
   Check2 <%= check_box_tag "search_inactive", "1", @search_inactive == 1) %> Inactive
   Check3 <%= check_box_tag "search_removed", "1", @search_removed == 1) %> Removed

如果您确实需要将它们放在一个数组中,您可以稍后轻松地将它们连接在一起。

相关文章: