I’m unable to find information on why this code fires the form submit when the input changes:
<form>
<input type="text" onchange="submit();">
</form>
I always thought that it has to be something like this:
<form>
<input type="text" onchange="this.form.submit();">
</form>
The input DOM element doesn’t have a function submit()
defined. Why does this work?
Edit:
This code snippet shows different behaviour. The button will run what is defined in onsubmit
of the form. But the change of the input will NOT do it, but instead do a form submit, omitting what is defined in onsubmit
of the form:
<form onsubmit="console.log('test'); return false;">
<input type="text" onchange="submit();">
<input type="submit">
</form>
Edit 2: as CBroe commented, onchange="submit();"
and onchange="this.form.submit();"
do the same thing. My confusion got the better of me.
The Question that remains is: why does onchange="submit();"
work? The input-element doesn’t have a function submit
defined.
3
Answers
Well, have you defined the submit() function ?
i think because you are using onchange() in javascript its an event listener, so if you enter an input, it will fire because it noticed a change in the form, you should use onclick() when submitted then it will fire at that moment. you should actually add it in the form tag not on the input like this
The submit() function is not defined for the input element in a form. This is because the submit() function is only defined for the form element itself. Therefore, calling this.form.submit() or SubmitForm(this.form) is the correct way to submit a form using JavaScript.
The error message "submit is not a function" occurs when the name or id of a form control is "submit", which masks the form’s submit method. Renaming the button to something else, such as "btnSubmit", will resolve the issue.