skip to Main Content

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


  1. Well, have you defined the submit() function ?

    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
  3. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search