我在表单中有几个复选框,我想将用户选择限制为3个复选框,因此当他选择3时,其余部分将被禁用(但如果他取消选择一个,则它们都会再次启用)。
目前我有这个代码,当用户试图检查第4个框时会弹出一条消息,但是我只是希望在选择了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');
}
});
答案 0 :(得分: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');
}
});