php - JavaScript 冲突?

标签 php javascript function

我在我的表单中的所有 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/

相关文章:

php - MySQL:查询中的符号

php - 无法创建存储过程 mysql 可能是 if else 语法

php - 如何在 PHP 中使用 implode 更新多个数据

c - 如何重新启动程序而不保存其值 (C)

c++ - 从 main 访问私有(private)字段和函数

function - 我可以使用存储在变量中的函数作为 Swift 中的运算符吗?

PHP-FPM With Opcache 尝试打开其他池的缓存文件

javascript - YouTube 视频 : fit content on non 16:9 father (as background-size: cover)

javascript - slider 无限循环停止

javascript - AngularJS 拖放事件监听器不起作用