我的HTML代码是这样的形式:name<form action="" method="post">
<input type="checkbox" name="sl[0]" />
<input type="checkbox" name="sl[1]" />
<input type="checkbox" name="sl[2]" />
<input type="checkbox" name="sl[3]" />
<input type="checkbox" name="sl[...]" />
</form>
请问各位如何才能实现限制最多的选中数目,一旦达到最大数目后,其它复选框变为不可选状态呢?感谢!

解决方案 »

  1.   

    <!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 type="text/javascript">
    function init(){
    var cs=document.getElementsByName("sl");
    for(var i=0;i<cs.length;i++){
    cs[i].onclick=function(){
    var num=0;
    for(var i=0;i<cs.length;i++){
    if(cs[i].checked){
    num++;
    }
    }
    if(num>=2){
    for(var i=0;i<cs.length;i++){
    if(!cs[i].checked){
    cs[i].disabled="disabled";
    }
    }
    }else{
    for(var i=0;i<cs.length;i++){
    if(!cs[i].checked){
    cs[i].disabled=false;
    }
    }
    }
    }
    }
    }
    window.onload=init;
    </script>
    </head><body>
    <form action="" method="post">
    <input type="checkbox" name="sl"/>1
    <input type="checkbox" name="sl" />2
    <input type="checkbox" name="sl" />3
    <input type="checkbox" name="sl" />4
    <input type="checkbox" name="sl" />5
    </form>
    </body>
    </html>这样试试
      

  2.   


    如果name属性一定要是这种形式,应该怎么实现?谢谢!
    <form action="" method="post">
    <input type="checkbox" name="sl[0]" />
    <input type="checkbox" name="sl[1]" />
    <input type="checkbox" name="sl[2]" />
    <input type="checkbox" name="sl[3]" />
    <input type="checkbox" name="sl[...]" />
    </form>
      

  3.   

    var cs=getElementsByTagName("input");
    for(var i=0;i<cs.length;i++){
    if(cs[i].type=="checkbox"){
    cs[i].onclick=function(){
    ....
    }
    }
    }
      

  4.   

    用jQuery吧,这个就3行代码的事儿
    <form action="" method="post">
    <input type="checkbox" name="sl[0]" />
    <input type="checkbox" name="sl[1]" />
    <input type="checkbox" name="sl[2]" />
    <input type="checkbox" name="sl[3]" />
    <input type="checkbox" name="sl[...]" />
    </form>
    最多选中3个
    <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
    <script>
    $('form').delegate('input[type="checkbox"][name^="sl\\["]', 'click', function (e){
    var boxes = $('input[type="checkbox"][name^="sl\\["]',this.form);
    boxes.filter(':not(:checked)').prop('disabled', boxes.filter(':checked').length >= 3);
    });
    </script>