Question

I have the following problem with Javascript. I'm trying to add an "onsubmit" handler automatically (after the page has been loaded) to every form element in the page. So I wrote this script:

window.onload=function(){
    var formElements=document.getElementsByTagName("form");
    for (var k=0;k<formElements.length;k++){
        formElements[k].onsubmit=function(param){
            return formValidator(param);
        }(formElements[k]);
    }
};

The formValidator function takes a form object as parameter, validates the content of the input and textarea elements inside the form and returns true or false as results of the validation. In the HTML file of the page I have a form element without the onsubmit attribute (that should be inserted by javascript).

The problem is that it seems that the form is automatically validated when the page is loaded (even if the user doesn't submit the form). And then if the user starts to insert data in the form and clicks the submit button the validateForm function doesn't execute.

Any ideas?

Thank you.

Was it helpful?

Solution

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).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top