首页 > 解决方案 > 自定义复选框 Rails / CSS

问题描述

我希望能够单击标签以检查我的元素而不显示已检查,所以我写了这个:

input[type="checkbox"]
{
   display: none;
 }

但是当我点击它不起作用。它仅在元素已经在数据库中时才有效。

我必须做javascript还是CSS可以做?

#views/values/edit.html.erb*

<% @values =["Power", "Independance", "Tradition"] %>
<%= form_for @resultvalue do |f| %>
   <% @values.each do | value | %>
       <%= f.check_box :values, { multiple: true }, value, type:"checkbox" %>
       <%= f.label value %>
   <% end %>
   <%= f.submit%>  
<% end %>
input[type="checkbox"]{
        display: none;
      }
      input[type="checkbox"]+label{
        transition: all 300ms ease;
        font-size: 1.2rem;
        cursor: pointer;
        border-radius: 1rem;
        border: 3px solid white;
        background-color: #0066cc;
        padding: 0.5rem 1rem;
        display: inline-block;
        color: white;

        // Suggested by @zizzo to prevent text selection
        -moz-user-select: -moz-none;
        -khtml-user-select: none;
        -webkit-user-select: none;
        -ms-user-select: none;
        user-select: none;
        // ------------------------


      }
      input[type="checkbox"]:checked+label{
        transition: all 300ms ease;
        background-color:#b70e7e;  
      }

标签: javascriptcssruby-on-railssassruby-on-rails-5

解决方案


输入标签上没有属性“multiple”,您也不需要设置type: 'checkbox',因为您已经在使用复选框助手,并且您正在传递:values我认为没有意义的。

要使标签正确更改复选框状态,您需要for使用相应复选框的 ID 正确设置属性https://developer.mozilla.org/es/docs/Web/HTML/Elemento/label

您还可以将输入标签嵌套在标签内,这样您就不需要该for属性。

最后,collection_check_boxes会比你的代码更干净https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-collection_check_boxes


推荐阅读