user1261591
user1261591

Reputation: 49

Onsubmit gets called on window.onload

first I am not JavaScript expert, just learning, trying to follow some tutorials. What I would like JavaScript to do is, when form has been submitted do a validation on the fields.

The code I wrote so far gets triggered on page load/reload, which is not desired functionality I am after. From what I understand this formFunction should be called only on onsubmit event. Guys if you see me something doing wrong please let me know. I would like to build a javascript function that will validate all forms on the page on submit Here are my JavaScript steps I came up with so far:

1 call checkForms function on window.onload

window.onload=checkForms; 

2 loop through all forms on the page and add onsubmit listener for the page forms

function checkForms(){
    for(var i=0; i<document.forms.length; i++){
        document.forms[i].onsubmit=thisForm(document.forms[i]);
    }
}

3 trigger thisForm function on submit

function thisForm(thisForm){
    var elements = thisForm.elements;
    var msg='';
    for(var i=0; i<elements.length; i++){
        msg += elements[i].name +'\n';
    }
    alert(msg);
    // this is where I want to send field values to be validated
}

Upvotes: 0

Views: 2630

Answers (1)

John Green
John Green

Reputation: 13435

here is your problem:

document.forms[i].onsubmit=thisForm(document.forms[i]);

You're calling thisForm() instead of setting it as function reference. The easiest thing to do is to make a closure:

document.forms[i].onsubmit=function(){thisForm(document.forms[i])};

Upvotes: 2

Related Questions