0

这是我的代码:

<script>                        
function validate(form) {   
    fail = validate_department(form);
    if (fail == "") { 
        return true;
        } else { 
            alert(fail);
            return false;
        }
    }
</script>
<script> 
    function validate_department(form) {
        if(!(form.operations.checked == true) && !(form.marketing.checked == true) && !(form.training.checked == true)){ return "You must enter at least one of the following: marketing, training, or operations.\n"; 
        }
        return "";
    }   

</script>
<form method="post" action="checkbox.php" onSubmit="return validate(this)">
<input type="checkbox" name="operations" value="operations" /> Operations <br>
                        <input type="checkbox" name="marketing" value="marketing" /> Marketing <br>
                        <input type="checkbox" name="training" value="training" /> Training
<input id="submit" type="submit" name="submit" value="Signup" />                        
</form>

如果我不检查任何内容,我想收到一条消息,告诉我我必须至少检查一个。

4

1 回答 1

0

试试这个validate功能。

function validate(form) {   
    fail = validate_department(form);
    if (fail == "") {
        for (var i = 0; i < form.elements.length; i++) {
            if (form.elements[i].type && (form.elements[i].type.toLowerCase() == 'checkbox')) {
                fail = "Please tick a checkbox at least one.";
                break;
            }
        }
    }
    if (fail != "") {
        alert(fail);
        return false;
    } else {
        return true;
    }
}
于 2012-11-05T19:06:16.463 回答