Disable button if all checkboxes are unchecked and enable it if at least one is checked

Viewed 17671

I have a table with a checkbox in each row and a button below it. I want to disable the button if at least one checkbox is checked.

<tbody>
    <tr>
        <td>
            <input class="myCheckBox" type="checkbox"></input>
        </td>
    </tr>
</tbody>
<button type=submit id="confirmButton"> BUTTON </button>

The jQuery I came up with to accomplish this is the following:

$('tbody').click(function () {
    $('tbody tr').each(function () {
        if ($(this).find('.myCheckBox').prop('checked')) {
            doEnableButton = true;
        }
        if (!doEnableButton) {
            $('#confirmButton').prop('disabled', 'disabled')
        }
        else {
            $('#confirmButton').removeAttr("disabled");
        }
    });
});

Naturally, this does not work. Otherwise I would not be here. What it does do is only respond to the lowest checkbox (e.g., when the lowest button is checked/unchecked the button is enabled/disabled).

I made a JSFIddle here although it does not show the same behaviour as locally.

Does any know how I can accomplish that it responds to all checkboxes and disables the button if they are ALL disabled?

4 Answers

Try this one:

let $cbs = $(".myCheckBox").change(function() {
    if ($cbs.is(":checked")){
        // disable #confirmButton if at least one checkboxes were checked
        $("#confirmButton").prop("disabled", false);
    } else {
        // disable #confirmButton if all checkboxes were unchecked
        $("#confirmButton").prop("disabled", true);
    }
});
Related