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

后端 未结 4 1187
轮回少年
轮回少年 2021-02-15 16:12

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.


    
         


        
4条回答
  •  星月不相逢
    2021-02-15 16:45

    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.

提交回复
热议问题