繁体   English   中英

如何在edit.html.erb中显示复选框“已检查状态”

[英]How to show checkbox 'checked state' in edit.html.erb

我的Rails应用程序中有复选框。 在填充表单中,一个复选框在选中时会变为蓝色。 提交表单后,用户尝试编辑/更新表单,即使选中该复选框,也不会显示“选中的颜色(蓝色)”复选框。 这使用户难以更新或编辑复选框。

我想要的是让用户在edit.html.erb中看到最初创建表单/记录时选中的复选框的选中(蓝色)状态。 这是new.html.erb中我的复选框代码的示例

<% Perk.all.each do |perk| %>
  <input type="checkbox", class="hidden" value="<%= perk.id %>" 
  name="company[perk_ids][]" id="company_perk_ids_<%= perk.id %>"/>
  <label class="category-choice" for="company_perk_ids_<%= perk.id %>">
<% end %>

这是我的js文件

    $(document).ready(function(){
      $(".category-choice").click(function(){
        $(this).toggleClass("active");
      });
    });

在我的CSS中,我有

 .category-choice {
  background: #CFCFD3;
  padding: 27px 15px 24px 10px;

  &.active {
    background: #51ADCF;
  }
}

在我的edit.html.erb中,该复选框的示例代码与new.html.erb中的代码相同

<% Perk.all.each do |perk| %>
 <input type="checkbox", class="hidden" value="<%= perk.id %>" 
 name="company[perk_ids][]" id="company_perk_ids_<%= perk.id %>"/>
 <label class="category-choice" for="company_perk_ids_<%= perk.id %>">
<% end %>

听起来像是TurboLinks问题。 是否将您的JS更改为这项工作?

(function() {
  $(document).on("turbolinks:load", function() {
    $(".category-choice").click(function(){
      $(this).toggleClass("active");
    });
  });
}).call(this);

在准备就绪时,您可以测试是否已检查元素。 因此,据此,您可以.toggleClass(function,[state])

片段:

 $("[id^='job_perk_ids_']").on('change', function (e) { $("[id^='job_perk_ids_']").not(this).removeAttr('checked'); $('label[for!=' + this.id + ']').removeClass('active'); var lbl = $('label[for=' + this.id + ']'); var isChk = $(this).is(":checked"); lbl.toggleClass(function(idx, className) { return "active"; }, isChk); }); // at dom ready $(".category-choice").toggleClass(function(idx, className) { var inpt = '#' + $(this).attr('for'); return $(inpt).is(":checked") ? "active" : ""; }); 
 .category-choice { background: #cfcfd3; padding: 27px 15px 24px 10px; } .category-choice.active { background: #51adcf; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="checkbox" class="hidden" value="perk.id" checked name="job[perk_ids][]" id="job_perk_ids_id0"/> <label class="category-choice" for="job_perk_ids_id0">my label0: checked</label> <input type="checkbox" class="hidden" value="perk.id" name="job[perk_ids][]" id="job_perk_ids_id1"/> <label class="category-choice" for="job_perk_ids_id1">my label1</label> </form> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM