Jquery how to count checked and disable checkboxes

后端 未结 7 1432
有刺的猬
有刺的猬 2021-02-15 12:29

I am trying to disable all unchecked checkboxes when there are 5 checked checkboxes.

My code is not working here it is: http://jsfiddle.net/mtYtW/18/

My Jquery:

7条回答
  •  你的背包
    2021-02-15 13:14

    Your code was close, with a few major issues.

    http://jsfiddle.net/mtYtW/37/

    $(function() {
        $('table input[type="checkbox"]').change(function() {
            var countchecked = $('table input[type="checkbox"]').filter(":checked").length
    
            if (countchecked >= 5) {
                $("table input:checkbox").not(":checked").attr("disabled", true);
            }else{
                $("table input:checkbox").attr("disabled", false);
            }
        });
    });
    

    The biggest, you had your code only executing onload. You need to execute it any time one of the checkboxes is checked, that is this part:

    $('table input[type="checkbox"]').change(function() {
    

    You had a misspelled variable name countcheck did not exist, it was countchecked.

    You were using find when you really wanted filter. Find will search in the descendants of the elements in your set, you wanted to filter them.

    You had > 5 when you stated you wanted to disable AT 5. So it should be >=.

    You were disabling ALL checkboxes, not just the unchecked as you stated, I added .not(":checked").

    And finally, I figured you would probably want to re-enable them if one was unchecked, so I added:

    }else{
        $("table input:checkbox").attr("disabled", false);
    }
    

提交回复
热议问题