I am trying to call a JavaScript function when the submit button of a form is clicked.
For some reason, the function is not called when it is named \'submit\', but when
Because submit()
is the reserved function to submit a form in core JS.
For example, if your form had an id like myform
, you could do this to submit it via JS:
document.form['myform'].submit();
So calling that function you're actually submitting the form and not calling your custom function.
EDIT: I forgot to mention, it only works inside the form because it's calling the submit function of that form. Out of it it's not available anymore (since the body tag doesn't have a submit function).
Form elements are placed on the scope chain of listeners within the form as if by:
with (form) {
/* run listener code */
}
so the identifier submit is first resolved in the context of the handler, then on the form before the rest of the scope chain. This is unique to forms and can be seen in the following:
<form>
<input name="foo">
<input type="button" value="Do click" onclick="
function submit(){console.log('click')};
submit();
">
</form>
where clicking the button runs the submit function within listener, and removing the function declaration runs the form's submit method. This is unique to forms.
Note that when a form's submit method is called directly, its submit handler is not called.
Outside of the form, the identifier submit is resolved in the normal way.