2
votes

I want to disable my button if no checkbox is checked. At least one checkbox should be checked to enable the button.

My 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>

I tried this jQuery code:

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

The button is disabled by default. When checked one checkbox it's enabled, when unchecked it's disabled again. But the problem is when I checked multiple checkbox and uncheck one checkbox it's disable again, though many checkbox is still checked.

2

2 Answers

5
votes

Instead of checking if the checkbox that was clicked is checked, you should check if any of the checkboxes are checked. You can do this by selecting all checked checkboxes with $('.checkbox:checked') and then checking the length of the returned jQuery object.

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

JSFiddle

4
votes

You need to see if any checkbox is check to make the decision on the disabled state.

Your should also use prop and not attr to ensure cross-browser compatibility.

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

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

prop for disabled can take a boolean flag value, so no need for the if else.