限制多选框选择数量

在网上找到的,可以使用。由于刷新后,多选框会保留选中的,这时数量达到要求后还是可以选择的bug,在前面加个判断数量是否数量达到要求的处理就可以了。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script>
$(function(){

//加上判断是否达到数量要求
    if($(":checkbox").size()>=3){
         $(":checkbox").removeAttr("checked");
         $(":checkbox").attr("disabled","disabled");
         $(":checkbox").removeAttr("disabled");
     }

    var num = 0;
    $(":checkbox").each(function(){
        $(this).click(function(){
            if($(this)[0].checked) {
                ++num;
                if(num == 3) {
                    //alert("最多选择 三项 的上限已满, 其他选项将会变为不可选.");
                    $(":checkbox").each(function(){
                        if(!$(this)[0].checked) {
                            $(this).attr("disabled", "disabled");
                        }
                    });
                }
            } else {
                --num;
                if(num <= 2) {
                    $(":checkbox").each(function(){
                        if(!$(this)[0].checked) {
                            $(this).removeAttr("disabled");
                        }
                    });
                }
            }
        });
    });
})
</script> 
</head>

<body>
<input type="checkbox" />上网<br />
<input type="checkbox" />旅游<br />
<input type="checkbox" />逛街<br />
<input type="checkbox" />游戏<br />
<input type="checkbox" />听歌<br />
<input type="checkbox" />购物<br />
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值