使用jQuery通过复选框禁用/启用按钮

Disable / Enable button by checkbox using jQuery

本文关键字:启用 按钮 复选框 jQuery 使用      更新时间:2023-09-26

如果未选中checkbox,我想禁用我的button。应至少检查一个checkbox以启用该按钮。

我的HTML:

<table border="1">
    <tr>
        <th></th>
        <th>Name</th>
    </tr>
    @foreach($clients as $client)
    <tr>
        <td><input type="checkbox" name="status[]" value="$client['id']" class="checkbox"></td>
        <td>{{ $client['name'] }}</td>
    </tr>
    @endforeach    
</table>
<button type="button" id="off" class="btn btn-default" data-toggle="modal" data-target="#offer" disabled>Choose New Offer</button>

我试过这个jQuery代码:

<script>
    $(function() {
        $('.checkbox').click(function() {
            if ($(this).is(':checked')) {
                $('#off').removeAttr('disabled');
            } else {
                $('#off').attr('disabled', 'disabled');
            }
        });
    });
</script>

默认情况下,该按钮为disabled。选中一个复选框时,它将被启用,未选中时,它会再次被禁用。但问题是,当我选中多个复选框并取消选中一个复选框时,它再次被禁用,尽管许多复选框仍然被选中。

您需要查看是否选中任何复选框来决定禁用状态。

您还应该使用prop而不是attr来确保跨浏览器兼容性。

$(function () {
  $('.checkbox').click(function () {
    $('#off').prop('disabled', !$('.checkbox:checked').length);
  });
});

JSFiddle:http://jsfiddle.net/TrueBlueAussie/L72Lv6h1/

disabledprop可以采用布尔标志值,因此不需要if else

与其检查是否选中了单击的复选框,不如检查是否选中任何复选框。您可以通过使用$('.checkbox:checked')选中所有选中的复选框,然后检查返回的jQuery对象的长度来完成此操作。

$(function() {
    $('.checkbox').click(function() {
        if ($('.checkbox:checked').length > 0) {
            $('#off').removeAttr('disabled');
        } else {
            $('#off').attr('disabled', 'disabled');
        }
    });
});

JSFiddle