【问题标题】:Disable / Enable button by checkbox using jQuery使用jQuery通过复选框禁用/启用按钮
【发布时间】:2016-03-09 11:38:09
【问题描述】:

如果没有选中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。检查一个复选框时,它已启用,当未选中它已再次禁用。但问题是当我选中多个复选框并取消选中一个复选框时,它再次被禁用,尽管许多复选框仍然被选中。

【问题讨论】:

    标签: javascript jquery html button checkbox


    【解决方案1】:

    您应该检查是否选中了任何复选框,而不是检查被单击的复选框是否被选中。您可以通过使用$('.checkbox:checked') 选中所有选中的复选框,然后检查返回的 jQuery 对象的长度来做到这一点。

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

    JSFiddle

    【讨论】:

    • 呜呼!谢谢兄弟。
    • 还有一个用于第一次进入
    【解决方案2】:

    您需要查看是否选中了 any 复选框以决定禁用状态。

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

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

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

    prop for disabled 可以采用 boolean 标志值,因此不需要 if else

    【讨论】:

    • $('#off').prop('disabled', $('.checkbox:checked').length &gt; 0); 需要为 $('#off').prop('disabled', $('.checkbox:checked').length === 0); 以适应 smartrahat 想要的行为。我试图进行编辑,但有字符限制。否则这比我的 +1 更好。
    • @spaniol6:是的,我注意到我把它颠倒了。已修复 ! 谢谢
    • 两个答案都对我有用。我应该接受哪个?
    • @spaniol6 最喜欢哪一个 :) - 他是第一名,但对于 disabledpropattr 更安全。
    • @smartrahat 这个是更好的答案:)
    猜你喜欢
    • 2020-12-28
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2018-11-07
    • 2015-08-02
    相关资源
    最近更新 更多