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