When onsubmit (or any other event) is supplied as an HTML attribute, the string value of the attribute (e.g. "return validate();"
) is injected as the body of the actual onsubmit handler function when the DOM object is created for the element.
Here's a brief proof in the browser console:
var p = document.createElement('p');
p.innerHTML = '<form onsubmit="return validate(); // my statement"></form>';
var form = p.childNodes[0];
console.log(typeof form.onsubmit);
// => function
console.log(form.onsubmit.toString());
// => function onsubmit(event) {
// return validate(); // my statement
// }
So in case the return
keyword is supplied in the injected statement; when the submit handler is triggered the return value received from validate
function call will be passed over as the return value of the submit handler and thus take effect on controlling the submit behavior of the form.
Without the supplied return
in the string, the generated onsubmit
handler would not have an explicit return statement and when triggered it would return undefined
(the default function return value) irrespective of whether validate()
returns true
or false
and the form would be submitted in both cases.