现场检查所有表格 [英] Checking all forms on site
问题描述
我需要检查我网站上的某些表格(〜10个).
我写了将改变输入类别的函数,因此它们将变为红色.
I need to check some forms (~10) on my site.
I wrote function which will change class of inputs, so they would become red.
function validate()
{
var result = true;
var inputList = document.getElementsByTagName("input");
for (var i=0; i<inputList.length; i++)
if (inputList[i].type == 'text')
{
if(inputList[i].value == "")
{
inputList[i].className='error';
inputList[i].onchange = function()
{
this.className='';
resetEvents(this);
}
result = false;
}
else
{
inputList[i].className='';
}
}
return result;
}
没有问题.我检查了一些形式,它工作正常.如果要提交表单,则应在onSubmit操作中添加return validate();
:
<form class='form' id='form' action='' method='post' onSubmit='return validate()'>
现在我需要设置所有形式的onSubmit-actions.
我想在加载的页面上分配表单处理程序:
There are no problems with it. I checked it with some forms and it works fine. If I want form to be submitted I should add return validate();
to onSubmit action:
<form class='form' id='form' action='' method='post' onSubmit='return validate()'>
Now I need to set onSubmit-actions of all forms.
I want to assign forms handler on page loaded:
window.onload = function() {
var formList = document.getElementsByTagName("form");
for (var i=0; i < formList.length; i++)
formList[i].onsubmit = return validate();
}
由于return validate();
,此代码不起作用,但是如果我删除了return
,并且将仅分配处理程序,则所有输入都将在页面加载时带有.error类.
This code don't work, because of return validate();
, but if I remove return
and will just assign handler all inputs would be with .error class already on page load.
要使此工作正确,我需要做什么?
What I have to make this working correct?
推荐答案
您需要将函数引用分配给onsubmit处理程序,而不是validate方法返回的值
you need to assign the function reference to the onsubmit handler, not the value returned by validate method
formList[i].onsubmit = validate; //this inside validate will refer to the submitted form
演示:小提琴
但是我更喜欢使用jQuery提交处理程序(validate方法中的this
将引用单击的表单)
But I will prefer to use jQuery submit handler(this
inside the validate method will refer to the clicked form)
jQuery(function(){
$('form').submit(validate)
})
演示:小提琴
注意:它有一个缺点,就是因为您从验证返回false
,它将阻止默认操作和提交事件的传播.
Note: it has one drawback, that is since you are returning false
from validate it will prevent both the default action and the propagation of the submit event.
这篇关于现场检查所有表格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!