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

回眸只為那壹抹淺笑 提交于 2020-01-31 08:54:15

问题


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?


回答1:


Try this:

var checkBoxes = $('tbody .myCheckBox');
checkBoxes.change(function () {
    $('#confirmButton').prop('disabled', checkBoxes.filter(':checked').length < 1);
});
checkBoxes.change(); // or add disabled="true" in the HTML

Demo

Explanation, to what I changed:

  • Cached the checkbox element list/array to make it a bit faster: var checkBoxes = $('tbody .myCheckBox');
  • removed the if/else statement and used prop() to change between disable= true/false.
  • filtered the cached variable/array checkBoxes using filter() so it will only keep the checkboxes that are checked/selected.
  • inside the second parameter of prop added a condition that will give true when there is more than one checked checkbox, or false if the condition is not met.



回答2:


Add an event handler that fires when a checkbox is changed, and see if there are any checked boxes, and set the disabled property appropriately :

var boxes = $('.myCheckBox');

boxes.on('change', function() {
    $('#confirmButton').prop('disabled', !boxes.filter(':checked').length);
}).trigger('change');

FIDDLE




回答3:


Try this:

$('tbody').click(function () {

   if ($('.myCheckBox:checked').length >= 1) { 
           $('#confirmButton').prop("disabled", true);
       }
   else {
            $('#confirmButton').prop("disabled", false);
   } 

 });

DEMO



来源:https://stackoverflow.com/questions/20687884/disable-button-if-all-checkboxes-are-unchecked-and-enable-it-if-at-least-one-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!