javascript - 在 Javascript 中验证多个表单

标签 javascript html

我有 2 个表格想要验证。由于某种原因,我只能验证一份表格。注意:在我的网页中,我使用 php 包含我的头文件(JS 验证脚本所在的位置)。我的问题是,使用以下格式验证多个表单的正确格式是什么?

<script type="text/javascript"> 

window.onload=function() {
  document.Form1.onsubmit=function() {
        ...
        field validating
        ...
    }
}

我已经尝试过这个,但一次只有一个可以工作(在本例中为 Form1,因为它是第一个):

<script type="text/javascript"> 

window.onload=function() {
  document.Form1.onsubmit=function() {
        ...
        field validating
        ...
    }

  document.Form2.onsubmit=function() {
        ...
        field validating
        ...
    }
}

谢谢!

编辑:这是一项作业,因此根本不需要完美:p

编辑 2: HTML 表单:

Table1.php
...
<form name="Form1" id="Form1" method="post" onSubmit="return(validate())">
...
Table2.php
...
<form name="Form2" id="Form2" method="post" onSubmit="return(validate())">
...

显然是 onSubmit 部分导致了问题?

最佳答案

您可以使用onsubmit为两者设置处理程序,将其作为参数传递以引用提交表单

function validate(ele) {
  var valid = true;

  // validate fields
  ele.text.style.borderColor = ele.text.value == '' ? 'red' : 'green'

  return valid;
}
<form id="form1" onsubmit="return validate(this);">
  <input name="text">
  <input type="submit" value="submit" />... ...
</form>
<form id="form1" onsubmit="return validate(this);">

  <input name="text">
  <input type="submit" value="submit" />... ...
</form>

或者您需要使用 document.forms[index] 带索引

console.log(document.forms)

window.onload = function() {
  document.forms[0].onsubmit = function() {
    alert(1);
    // do validation here
  }

  document.forms[1].onsubmit = function() {
    alert(2);
    // do validation here
  }
}
<form id="form1" onsubmit="return validate(this);">
  <input name="text">
  <input type="submit" value="submit" />... ...
</form>
<form id="form2" onsubmit="return validate(this);">

  <input name="text">
  <input type="submit" value="submit" />... ...
</form>

关于javascript - 在 Javascript 中验证多个表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676474/

相关文章:

javascript - 纯 JavaScript 编程

PHP li值在sql查询中使用

javascript - 单击时如何使标签不透明?

html - 当鼠标位于固定 div 顶部时无法滚动

javascript - 物体在低速时不遵守反射定律

javascript - nodejs中前端向后端写入JSON数据

javascript - 使用 PHP 的 CORS(跨源资源共享)

css - 元标记 "viewport"内容 ="width=device-width"不工作

javascript - 视频 'autoplay' 仅有时成功

ruby-on-rails - 包括带有 :cache => true into a rails app 的大型 JS 库