【问题标题】:Simple form builder checkbox collection custom html input简单表单生成器复选框集合自定义 html 输入
【发布时间】:2024-01-20 02:17:01
【问题描述】:

使用 simple_form_for,应该如何构建像颜色选择器这样的东西?想象一个页面,用户可以通过选中复选框来选择要使用的多种颜色。我想展示一个带有颜色的小框和旁边的复选框,以便用户可以通过选中复选框来选择颜色。像这样的

<input type="checkbox" name="colors[test]"><div style="background-color: red; width: 20px; height: 20px"></div>
<input type="checkbox" name="colors[test]"><div style="background-color: green; width: 20px; height: 20px""></div>
<input type="checkbox" name="colors[test]"><div style="background-color: blue; width: 20px; height: 20px""></div>

【问题讨论】:

    标签: ruby-on-rails checkbox simple-form


    【解决方案1】:

    您可以将 html 标签添加到集合中并为每个标签定义类。然后相应地设置它们的样式。我假设你有一个simple_form_for @color 或类似的东西。

    <%= f.input :test, :label => 'Choose a Color:', :collection =>{'<div class="red colorbox"></div>'.html_safe => 'red', '<div class="green colorbox"></div>'.html_safe => 'green', '<div class="blue colorbox"></div>'.html_safe => 'blue' }, :as => :check_boxes %>
    

    在您的样式表中:

    /* The colorbox will be under a label with collection_check_boxes class.*/
    .collection_check_boxes {
      width: 30px;
      height: 20px;
    }
    
    .colorbox {
      width: 20px;
      height: 20px;
    }
    
    .red {background: red;}
    .green {background: green;}
    .blue {background: blue;}
    

    【讨论】:

    • 谢谢!这对我来说simple_form 似乎有点混乱。看起来并不简单:)。现在,我还要求我必须将颜色分组。所以像“Colors.all.in_groups_of(4, false)”这样的东西应该是如何组织的。把它收藏起来似乎没有帮助,可以吗?集合中的所有内容都被统一处理?
    • 分组是什么意思?你的意思是每行有 4 个复选框还是别的什么?
    • 右...一行4个复选框。
    • 虽然我现在不知道,但你可以尝试添加换行符。例如:collection =&gt;{'&lt;div class="red colorbox"&gt;&lt;/div&gt;'.html_safe =&gt; 'red', '&lt;div class="green colorbox"&gt;&lt;/div&gt;&lt;br/&gt;'.html_safe =&gt; 'green', '&lt;div class="blue colorbox"&gt;&lt;/div&gt;'.html_safe =&gt; 'blue' }。在绿色之后添加&lt;br/&gt;
    • 再次感谢!不幸的是,这在我的情况下是不可能的,因为我不知道我会从外部馈送系统获得多少种颜色。我可以得到 10 个,我可以得到 20 个。我必须分成 4 个并用一个 div 进行变形,这样我就可以设置它的样式了。