Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript, onsubmit

I am trying to understand why onsubmit at Javascript is using an anonymous function to get it value like that:

onsubmit = function() {return validForm();}

I know that onsubmit is taking a true or false values, but i can't understand how does the anonymous function is necessary to get the value of true or false for the onsubmit event, like this:

onsubmit = validForm();

I will be very thankful if some one can please help me understand this, Thank you all and have a nice day.

like image 981
Aviel Fedida Avatar asked Sep 22 '26 02:09

Aviel Fedida


2 Answers

A valid assignment would be:

onsubmit = validForm;

You're assigning the function called validForm as the onsubmit handler. But, when you do this:

onsubmit = validForm();

You're assigning the result of calling the function validForm to the onsubmit handler. Unless validForm is returning a function, this won't work.

The reason the anonymous function assignment above works is, it is assigning a function to the onsubmit handler -- a function that in turn calls the validForm function when it is called.

like image 162
Ates Goral Avatar answered Sep 24 '26 16:09

Ates Goral


You are calling validForm and setting onsubmit to its return value. In example:

function foo () {
    return "hi";
}

onsubmit = foo() // eq to onsubmit = "hi";

onsubmit = foo // onsubmit now has the same function as foo
like image 40
Austin Avatar answered Sep 24 '26 16:09

Austin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!