【问题标题】:If Checkbox is Checked Keep DIV hidden even on page reload如果选中复选框,即使在页面重新加载时也要隐藏 DIV
【发布时间】:2019-07-18 06:51:57
【问题描述】:

我有一个 rails 表单。当一个复选框被选中时(在数据库中为真),我想保持 div 隐藏。我找到了其他解决方案,但在页面重新加载时它会重新出现,如果选中或为真,我想保持 div 隐藏。

  <div class="form-group">
    <%= form.check_box :tos_checkbox, class: "terms_of_services" %>
    <%= form.label :tos_checkbox, "Agree to TOS" %>
  </div>

  <div id="hide_if_above_checked">
    Do You Agree to Our TOS
  </div>

我知道这个脚本行不通,但一直在尝试几个不同的例子来解决我的问题。

  $(function () {
      $('.terms_of_services').change(function () {
          if(checkbox.checked == true){
              document.getElementById("hide_if_above_checked").setAttribute("d-none");
          }else{
              document.getElementById("hide_if_above_checked").removeAttribute("d-none");
          }
      });
  });

【问题讨论】:

    标签: javascript jquery ruby-on-rails checkbox


    【解决方案1】:

    从db调用复选框值并在渲染时检查

     <%if @variable_of_current_model.tos_checkbox != 'true' %>
      <div id="hide_if_above_checked">
       Do You Agree to Our TOS
     </div>
    <% end %>
    

    div#hide_if_above_checked 只会在数据库不真实时显示。

    【讨论】:

    • 太棒了。欣赏它!我也喜欢这种方法。
    【解决方案2】:

    要持久化数据,您需要使用window.localStoragewindow.sessionStoragedocument.cookie

    您的后端甚至可以访问 Cookies

    【讨论】:

      【解决方案3】:

      您可以在页面加载时获取复选框的值。

      if ($(".terms_of_services").is(':checked')){
        $("#some-div-box").hide();
      }else{
        $("#some-div-box").show();
      }
      

      这样,如果复选框被选中,那么你可以隐藏 div。

      【讨论】:

        【解决方案4】:

        添加到您的 CSS

        .hidden-div {
          display: none;
        }
        

        然后

        <div id="hide_if_above_checked" class="<%= 'hidden-div' if tos_checkbox %>">
          Do You Agree to Our TOS
        </div>
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-04-24
          • 2012-06-27
          相关资源
          最近更新 更多