Disable / Enable button by checkbox using jQuery

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.

Answers


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.


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


Need Your Help

Do I need to bind result when fetching all results for security?

php sql sql-injection sqlbindparameter

I am fairly new to MySQL so my apologies if this sounds like a silly question.

How to prevent a disabled JMenuItem from hiding the menu when being clicked?

java swing jpopupmenu jmenuitem

In my Java swing application i have noticed that when i click on a disabled JMenuItem in a JPopupMenu it hides the menu, but i i do not want to hide it, as if nothing is clicked. Is there a way to