簡體   English   中英

驗證JavaScript中的多種形式

[英]Validating multiple forms in Javascript

我有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> 

或者您需要使用帶有index的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> 

您指向根document上未定義的屬性。 嘗試使用document.forms集合: https : //developer.mozilla.org/en-US/docs/Web/API/Document/forms

示例 document.forms['formID'].onsubmit

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM