利用html和JavaScript写一个包含复选框的表单验证,复选框至少选中两个选项
时间: 2024-05-21 22:10:19 浏览: 53
一个关于JavaScript的表单验证
<!DOCTYPE html>
<html>
<head>
<title>复选框表单验证</title>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()">
<label>
<input type="checkbox" name="option1" value="option1">选项1
</label><br>
<label>
<input type="checkbox" name="option2" value="option2">选项2
</label><br>
<label>
<input type="checkbox" name="option3" value="option3">选项3
</label><br>
<label>
<input type="checkbox" name="option4" value="option4">选项4
</label><br>
<label>
<input type="checkbox" name="option5" value="option5">选项5
</label><br>
<input type="submit" value="提交">
</form>
<script>
function validateForm() {
var checkboxes = document.getElementsByName("option");
var checkedCount = 0;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checkedCount++;
}
}
if (checkedCount < 2) {
alert("请至少选择两个选项");
return false;
} else {
return true;
}
}
</script>
</body>
</html>
阅读全文