我在我的表单中的所有HTML下都有一些验证代码,这可以防止我的复选框验证代码无法正常工作,一旦我在HTML下的代码周围添加了/ * * /(这使得它处于非活动状态),我就来到这个结论)复选框验证代码开始正常工作。顺便说一句,两个单独的验证工作正常。有谁可能解释为什么会这样,因为我需要两个验证工作?这是我的代码:
<script>
function validateCheckBoxes(theForm) {
if (!theForm.declare.checked) {
alert ('You must tick the checkbox to confirm the declaration');
return false;
} else {
return true;
}
}
</script>
<form name="form" method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="eoi" onsubmit="return validateCheckBoxes(this);">
<b>Post Code</b>
<br>
<input type="text" id="post" name="post"><?php echo $msgp; ?>
<b>Declaration</b>
<input type="checkbox" name="declare" id="declare">
<input type="submit" name="submit" id="submit" value="submit">
</form>
<script>
var form = document.getElementById('eoi'),
validNumbers = [2474,
2750,
2753,
2760,
2777];
form.onsubmit = function() {
var userInput = document.getElementById("post"),
numb = parseInt(userInput.value, 10);
if ( validNumbers.indexOf(numb) == -1 ) {
alert("Please enter a correct postcode");
return false;
} else {
return true;
}
}
</script>
答案 0 :(得分:2)
在您的代码中,问题是您为表单注册了两个onsubmit
处理程序,最新的处理程序将覆盖前一个。
在这里,我将两个验证移动到一个onsubmit
处理程序,它首先验证邮政编码,然后验证声明复选框。
<form name="form" method="POST" action="" id="eoi">
<b>Post Code</b>
<br/>
<input type="text" id="post" name="post"/>asdf
<b>Declaration</b>
<input type="checkbox" name="declare" id="declare"/>
<input type="submit" name="submit" id="submit" value="submit"/>
</form>
和
function validateCheckBoxes(theForm) {
console.log('asdf')
if (!theForm.declare.checked) {
alert ('You must tick the checkbox to confirm the declaration');
return false;
} else {
return true;
}
}
var form = document.getElementById('eoi'),
validNumbers = [2474,
2750,
2753,
2760,
2777];
form.onsubmit = function() {
var userInput = document.getElementById("post"),
numb = parseInt(userInput.value, 10);
if ( validNumbers.indexOf(numb) == -1 ) {
alert("Please enter a correct postcode");
return false;
}
return validateCheckBoxes(form);
}
演示:Fiddle