【问题标题】:jquery disable checkboxes when number of selected options reaches a certain point [duplicate]当所选选项的数量达到某个点时,jquery禁用复选框[重复]
【发布时间】:2014-05-18 22:04:42
【问题描述】:

我在一个表单中有几个复选框,我想将用户的选择限制为 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');
}
});

【问题讨论】:

    标签: jquery events click


    【解决方案1】:

    试试这个:

    $('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"]').not(':checked').prop('disabled',false); 代替$('input[type="checkbox"]').not(':checked').removeProp('disabled');。
    • 但该字段仍将是 disabled 和 prop('disabled', false)
    • 试试this demo。很容易混淆属性和属性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-21
    • 2012-05-08
    • 2018-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    相关资源
    最近更新 更多