Checking all forms on site

2019-09-07 04:48发布

问题:

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;
}

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();
}

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?

回答1:

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

Demo: Fiddle

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

Demo: Fiddle

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.