【问题标题】:Enable checkbox if other checkbox is checked如果选中其他复选框,则启用复选框
【发布时间】:2017-11-02 23:50:47
【问题描述】:

我有一个包含多列的表格,其中 2 个是复选框。但是,我只希望在页面加载时启用第一列复选框。如果在第一列中选​​中了复选框,我只希望启用第二列复选框。

我当前的代码会这样做,但我希望选中的复选框仅启用/禁用同一行中的特定复选框,而不是整个列中的所有复选框。

我该怎么做?这是我目前所拥有的:

$(document).ready(function() {
  $('.paid').attr('disabled', true);

  $('.selected').change(function() {
    $('.paid').attr('disabled', !this.checked);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--checkbox that is enabled on page load-->
<td align="center"><input type="checkbox" id="check" class="selected" name="selected"></td>

<!--checkbox that will be enabled/disabled based on checkbox above-->
<td align="center"><input type="checkbox" id="paid" class="paid" name="selected"></td>

【问题讨论】:

  • 给该复选框一个唯一的ID并相应地应用js
  • 如果我们可以看到表格的所有 html,或者至少可以看到完整的表格行,那么您的问题就很容易回答了。可以上传吗?
  • @SanchitPatiyal 我不同意。作为表格数据,这有助于使用closest('tr'),然后查找不是自身的复选框。在这个用例中,id 或类不是必需的。
  • 我没有说它们在不同的行中。他说它们在同一行,这就是最接近()方法有效的原因。
  • @Taplar 非常感谢您的纠正

标签: javascript jquery html checkbox


【解决方案1】:

$(document).ready(function() {
  $('.paid').attr('disabled', true);

  $('.selected').change(function() {
    //find only the paid in the same row as the selected checkbox
    $(this).closest('tr').find('.paid').attr('disabled', !this.checked);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <table id="myTable">
            <tr>
                <td align="center"><input type="checkbox" id="check" class="selected" name="selected"></td>
                <td align="center"><input type="checkbox" id="paid" class="paid" name="selected"></td>
            </tr>
            <tr>
                <td align="center"><input type="checkbox" id="check" class="selected" name="selected"></td>
                <!-- checkbox that will be enabled/disabled based on checkbox above --> 
                <td align="center"><input type="checkbox" id="paid" class="paid" name="selected"></td>
            </tr>

        </table>

【讨论】:

    【解决方案2】:

    这应该可以解决问题:

    $(document).ready(function () {
      $('.paid').attr('disabled', true);
    
      $('.selected').change(function(){
        $(this).parent().siblings().find('.paid').attr('disabled', !this.checked);
      });
    });
    

    这将确保它在您的 .selected 复选框旁边找到 .paid 复选框。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-09
      • 2016-09-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多