当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery多选框选择数量限制方法

jQuery多选框选择数量限制方法

2019年03月26日  | 移动技术网IT编程  | 我要评论

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

<html>
<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>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网