Javascript clashing?

Javascript clashing?

本文关键字:clashing Javascript      更新时间:2023-09-26

我有一些验证代码在所有的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);
}    

演示:小提琴