我在我的文件中编写了一个代码,用于验证适用于大多数浏览器(包括safari)的登录表单,但突然在一周前它停止了复选框的工作。如果我在没有选择服务的情况下提交表单,那么它会提交哪些不应该发生。这是我的下面的代码,如果有人能指出它停止工作的原因会很棒。提前谢谢!
<form method="post" action="includes/blah.php" name="GuestForm" id="GuestForm" autocomplete="off" onsubmit="return validate();">
<input name="services[]" type="checkbox" value="blah"> blah<br>
<input name="services[]" type="checkbox" value="blah2"> blah2<br>
<input name="services[]" type="checkbox" value="blah3"> blah3<br>
<input type="submit" class="submit" id="submit" value="Submit"><input type="reset" value="Reset"><br>
</form>
<script>
function validate(){
if(!document.getElementById('services[]').checked){
alert('Please choose a service');
return false;
}
return true;
}
</script>
答案 0 :(得分:1)
<script>
function validate(){
var services = document.getElementsByName('services[]');
for(k=0; k < services.length; k++) {
if (services[k].checked) return true;
}
alert('Please choose a service');
return false;
}
</script>
编辑以获得确切答案:
<script>
function validate(){
var services = document.getElementsByName('services[]');
var services_length = services.length;
if (services_length) {
var unchecked = true;
for(k=0; k < services_length; k++) {
if (services[k].checked) {
unchecked = false;
break;
}
}
if (unchecked) {
alert('Please choose a service');
return false;
}
}
return true;
}
</script>