You're calling your handler function, and assigning the result of calling it to onsubmit
. (The (formElements[k])
after the function calls it.)
You need to refer to the function without calling it. One good way to do that in the general case is to use a builder function (but see below for why that general case probably doesn't apply here):
window.onload=function(){
var formElements=document.getElementsByTagName("form");
for (var k=0;k<formElements.length;k++){
formElements[k].onsubmit=buildHandler(formElements[k]);
}
function buildHandler(form) {
return function(){
return formValidator(form); // <== I'm guessing `formvalidator` takes the form
};
}
};
But there's no need to create a separate handler for each form. The way you're assigning the handler, this
will be the form
element, so just:
window.onload=function(){
var formElements=document.getElementsByTagName("form");
for (var k=0;k<formElements.length;k++){
formElements[k].onsubmit=handler;
}
function handler(){
return formValidator(this);
}
};
The thing about this
being the element will be true when you assign functions to onxyz
properties on DOM elements, when you use attachEvent
(on IE), or when you use addEventListener
(standard). It is not true if you call a function from onxyz
attributes in the markup, e.g. onsubmit="foo()"
(although you can use onsubmit="foo.call(this);"
and it will be).