日期:2014-05-16  浏览次数:20428 次

判断checkbox是否选中
在一个form中,同时有checkbox和submit提交按钮。现在想达到的效果是,当checkbox选中时,submit按钮才能提交;否则提示返回。请问如何做到?最好有代码示例,谢谢!

------解决方案--------------------
HTML code

<!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=gb2312" />
<title></title>
</head>
<script>
window.onload = function(){
    document.getElementById("btn").onclick=function(){
        var flag1 = document.getElementById("ckb1").checked;
        if(!flag1){
            alert("请先选择复选框1");
            return false;
        }
        var flag2 = document.getElementById("ckb2").checked;
        if(!flag2){
            alert("请先选择复选框2");
            return false;
        }
        alert("提交表单");
        return true;
    }
}
</script>
<body>
<input id="ckb1" type="checkbox"/>
<input id="ckb2" type="checkbox" checked="checked"/>
<input id="btn" type="submit" value="submit"/>
</body>
</html>

------解决方案--------------------
HTML code
<input type="checkbox" name="checkbox[]" value="原因A" />原因A<br />
<input type="checkbox" name="checkbox[]" value="原因B" />原因B<br />
<input type="checkbox" name="checkbox[]" value="原因C" />原因C<br />
<input type="checkbox" name="checkbox[]" value="others" />其他
<input type="text" id="txt" name="reason" style="display:none;" />
<input id="btnEditOK" type="Submit" disabled="true" class="btnbig" value="提交" onmouseover="this.className='btnbig_over'" onMouseOut="this.className='btnbig'" />
<script type="text/javascript">
    var input=document.getElementsByName("checkbox[]");
    var txt = document.getElementById("txt");
    var btnEditOK = document.getElementById("btnEditOK");
    for(var i=0;i<input.length;i++){
        input[i].onclick=function(){
            var n=0;
            for(var l=0;l<input.length;l++){
                txt.style.display="none";
                if(input[l].checked){
                    n++;
                    if(input[l].value=="others"){
                        txt.style.display="";
                    }
                }
            }
            if(n==0){
                btnEditOK.disabled=true;
            }else{
                btnEditOK.disabled=false;
            }
        }
    }
</script>

------解决方案--------------------
HTML code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta http-equiv="Content-Type" content="text/html" charset="gbk"/>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
 </head>
<script type="text/javascript">
    function check(){
        var checkBox=document.getElementsByTagName("input");
        var i,num=0;
        for(i=0;i<checkBox.length-1;i++){
            if(!check