【问题标题】:Rails: Disable form field when checkbox is checkedRails:选中复选框时禁用表单字段
【发布时间】:2015-02-02 23:33:30
【问题描述】:

在我的 Rails 应用程序中,我的表单中有这两个字段,并且我试图在选中复选框时禁用 end_date 字段,但没有成功,所以我想知道如何实现这一点? 这是我的表格

<%= f.date_select :end_date, start_year: 1945 %> 
<%= f.check_box :is_current %>

【问题讨论】:

    标签: javascript jquery ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    尝试将此添加到您的 javascript 文件中,它应该可以正常工作。

    $( document ).ready(function() {
        $("#checkBox_id").click(function() {
            var isDisabled = $(#checkBox_id).prop('checked')
            if(isDisabled) {
                $("#endDate_id").removeAttr("disabled");
            } else {
                $("#endDate_id").prop('disabled', true)
            }
        });
    });
    

    【讨论】:

    • 我的错,删除脚本标签。
    【解决方案2】:

    简单的 JS

    $(document).ready(function() {
      return $("#dateCheck").click(function() {
        return $("#endDate").prop("disabled", !this.checked);
      });
    });
    

    HTML

    <body>
        <input type="checkbox" id="dateCheck" unchecked/>
        <input type="date" id="endDate" />
    </body
    

    【讨论】:

    • 请解释“没用”。它出错了吗?它显示了复选框和日期字段,但禁用功能不起作用?
    • 好的,忘记了我的 $(document... 刚刚将它添加到 Rails 应用程序中,它就可以工作了。
    【解决方案3】:

    这应该可行。当复选框被选中时,Rails 中默认的date_select 生成的每个select 字段都将被禁用。如果这仍然不能解决您的问题,请发布您的完整表格,以便我们更好地了解正在发生的事情。

    $(document).ready(function() {
      $("[id*='is_current']").click(function() {
        var isCurrent = $(this).prop("checked");
        var endDateSelects = $("[id*='end_date']");
        if (isCurrent == true) {
          endDateSelects.prop("disabled", "disabled");
        }
        else {
          endDateSelects.prop("disabled", false);
        }
      });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多