簡體   English   中英

使用jQuery禁用/啟用按鈕

[英]Disable / Enable button by checkbox using jQuery

如果沒有checkbox我想禁用我的button 應至少checkbox一個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該按鈕。 當選中一個復選框時,它被啟用,當取消選中時,它再次被禁用。 但問題是,當我選中多個復選框並取消選中一個復選框時,它會再次禁用,但仍會檢查許多復選框。

不檢查是否選中了單擊的復選框,而應檢查是否選中了任何復選框。 您可以通過選中所有選中的復選框和$('.checkbox:checked')然后檢查返回的jQuery對象的長度來完成此操作。

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

的jsfiddle

您需要查看是否檢查了任何復選框以對禁用狀態做出決定。

您還應該使用prop而不是attr來確保跨瀏覽器兼容性。

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

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

propdisabled可以采取一個布爾標志值,因此無需為if else

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM