CastleNation
CastleNation

Reputation: 1

Javascript - onsubmit activating on pageload

I have the following javascript code.

window.onload = function init() {


var appForm = document.getElementById("application");
appForm.onsubmit = validate();

}

I want the validate function to only occur once someone has clicked the 'submit' button on the page, but the form is validating as soon as the page loads. What do I need to change to fix this? Thanks!

edit: Thanks bozdoz, that worked perfectly.

Upvotes: 0

Views: 904

Answers (1)

StackSlave
StackSlave

Reputation: 10627

You are executing the function which probably doesn't return another unexecuted function. onsubmit must be assigned a function name, which is basically a variable, or an Anonymous function. Change

appForm.onsubmit = validate();

to

appForm.onsubmit = validate;

or

appForm.onsubmit = function(){
  validate(arg0, arg1, arg2); // preferred way if your function takes arguments
}

Note that when any JavaScript Event occurs the only thing that is passed to the Anonymous function or a function like validate is just the Event Object, so you must pass arguments of your own using the bottom example.

Upvotes: 1

Related Questions