当所选选项数达到某一点时,jquery禁用复选框

当所选选项数达到某一点时,jquery禁用复选框,jquery,events,click,Jquery,Events,Click,我在一个表单中有几个复选框,我想将用户的选择限制为3个复选框,因此当他选择3个复选框时,其余的复选框将被禁用(但如果他取消选择一个复选框,它们将再次被启用) 目前我有这个代码,当用户试图选中第四个框时会弹出一条消息,但是我只希望在选中三个框后所有框都被禁用 $('input[type="checkbox"]').click(function(event) { if (this.checked && $('input:checked').length > 3) { e

我在一个表单中有几个复选框,我想将用户的选择限制为3个复选框,因此当他选择3个复选框时,其余的复选框将被禁用(但如果他取消选择一个复选框,它们将再次被启用)

目前我有这个代码,当用户试图选中第四个框时会弹出一条消息,但是我只希望在选中三个框后所有框都被禁用

$('input[type="checkbox"]').click(function(event) {
if (this.checked && $('input:checked').length > 3) {
    event.preventDefault();
    alert('You\'re not allowed to choose more than 3 boxes');
}
});
试试这个:

$('input[type="checkbox"]').change(function(event) {
    if ($('input[type="checkbox"]:checked').length >= 3) {
        event.preventDefault();
        $('input[type="checkbox"]').not(':checked').prop('disabled', true);
        alert("You're not allowed to choose more than 3 boxes");
    }
    else if {
        $('input[type="checkbox"]').not(':checked').removeProp('disabled');
    }
});

为了获得更一致的行为,我将使用
$('input[type=“checkbox”]”)。而不是(':checked')。prop('disabled',false)
代替
$('input[type=“checkbox”]”)。不(':checked')。移除属性('disabled')。但该字段仍将被
禁用
,使用
prop('disabled',false)
重试。很容易混淆属性和属性。