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

JS验证radio和checkbox是否被选
<html>
<head>
    <title></title>
    <script src="JavaScript.js"></script>
    
</head>


<body>
    <form id="form" name="form" method="post" action="http://js.aiyiweb.com" onsubmit="return CheckForm()">
        <input type="checkbox" name="love" >
        <input type="checkbox" name="love" >
        <input type="checkbox" name="love" >
        <input type="checkbox" name="love" >
        


        <input type="radio" value="好的" name="miaoshu" >
        <input type="radio" value="好的" name="miaoshu" >
        <input type="radio" value="好的" name="miaoshu" >
        <input id="txtbox" name="MyTextfield" type="text">
        
        <input type="submit" value="提交" >
    </form>


</body>
</html>




function CheckForm() {
    var flag = false;
    var allRadio = document.form.elements["miaoshu"];
    var txtBox = document.getElementById("txtBox").value;
    for (var i = 0; i < allRadio.length; i++) {
        if (allRadio[i].checked) {
            if (allRadio[allRadio.length - 1].checked) {
                if (txtBox == "") {
                    flag = false;
                }
                else {
                    flag = true;
                }

            }
        }
    }
    if (!flag) {
        alert("请确定输入完整");
    }

    var cbxs = document.getElementsByName('love');
    var s = 0;
    for (var i = 0; i < cbxs.length; i++) {
        if (cbxs[i].checked)
        { s += 1; }
    }
    if (s < 1) {
        alert("请确定输入完整");
        flag = false;
    }
    return flag;
}