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

后端 未结 4 1172
轮回少年
轮回少年 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:37

    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);
        }
    });
    
    0 讨论(0)
  • 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.
    0 讨论(0)
  • 2021-02-15 16:47

    Try this:

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

    DEMO

    0 讨论(0)
  • 2021-02-15 16:53

    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

    0 讨论(0)
提交回复
热议问题