我在我的表单中的所有 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>
最佳答案
在您的代码中,问题是您为表单注册了两个 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
关于php - JavaScript 冲突?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16713150/