如何在选中复选框时禁用文本框,并在取消选中复选框时启用文本框

时间:2019-04-04 14:57:51

标签: jquery

我有两个类型为text的输入字段,我想在选中复选框时禁用它们,而在我使用jquery取消选中复选框时启用它们

这是我的代码:

 <div class="col-md-11" id="worktimeID">
                <input  type="text" name="From_1" class="time" placeholder="00:00" />
                <input type="text" name="To_1" class="time" placeholder="00:00" />
                <input type="checkbox" id="checked"/><label>Day Off ?</label>

            </div>

我的jquery代码:

$("#checked").click(function () {
        if ($(this).is(":checked")) {
            var worktime = $(this).closest("div").attr("id");
            var allTextBoxes = $(worktime).children('[type=text]');

            alert(allTextBoxes);
            allTextBoxes.prop('disabled', true);
        }
        else {
            var worktime = $(this).closest("div").attr("id");
            var allTextBoxes = $('[type=text]');
            $('#checked').attr('checked', false);
            allTextBoxes.prop('disabled', false);

        }


    });

1 个答案:

答案 0 :(得分:1)

  1. worktime只是ID,没有哈希。但是选择器需要哈希。

  2. 您甚至没有在其他地方使用worktime,所以不确定为什么要这么做。

    $("#checked").click(function () {
        if ($(this).is(":checked")) {
            var worktime = $(this).closest("div").attr("id");
                               // #1
            var allTextBoxes = $('#'+ worktime).children('[type=text]');
    
            alert(allTextBoxes);
            allTextBoxes.prop('disabled', true);
        }
        else {
            // #2
            var worktime = $(this).closest("div").attr("id");
            var allTextBoxes = $('[type=text]');
            $('#checked').attr('checked', false);
            allTextBoxes.prop('disabled', false);
    
        }
    });
    
  3. 在任何情况下,都可以简化此逻辑,因为如果选中此复选框,则应禁用它们。如果未选中,则不会被禁用。

        $("#checked").click(function() {
          $(this).closest("div").find(':text').prop('disabled', this.checked);
        });
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <div class="col-md-11" id="worktimeID">
          <input type="text" name="From_1" class="time" placeholder="00:00" />
          <input type="text" name="To_1" class="time" placeholder="00:00" />
          <input type="checkbox" id="checked" /><label>Day Off ?</label>
        </div>