1

Let's say we have an HTML like this one:

<form id="myform" action="http://google.com/">
    Your Email: <input type="email" id="email">
    <input type="submit" name="">
</form>

I did a few tests, and input#email "change" event always came before form#myform "submit" event.

Should this behavior be expected in all major browsers?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Sergey
  • 47,222
  • 25
  • 87
  • 129
  • 1
    Event order doesn't appear to be guaranteed in any respect. It is up to each Browser to invent their own precedence paradigms. Logically the answer is that the change event will always come before submit, but if you are concerned you can always create your own event( a middle function so to speak ) that triggers events in the order you want. – zfrisch Apr 02 '18 at 16:59
  • 1
    I would say yes, the change will call first, unless the "submit" is JavaScript. If that's the case, it's asynchronous, and it can be intermittent that either one run before or after the other. If they are both running via JS, I would run one inside the other with a callback to ensure that they run synchronous. – Zak Apr 02 '18 at 17:00
  • Possible duplicate of [What is the event precedence in JavaScript?](https://stackoverflow.com/questions/282245/what-is-the-event-precedence-in-javascript) – zfrisch Apr 02 '18 at 17:05

1 Answers1

1

Yes and no.

From a practical perspective, it's a pretty safe bet that all browsers will process a change before a submit (barring calls directly triggered by JavaScript).

document.querySelector('form').addEventListener('submit', e => { console.log('submit'); e.preventDefault(); });
document.querySelector('input').addEventListener('change', () => console.log('change'));
<form>
  <input>
</form>

That said, there isn't any specific specification that requires this behavior. The closest is probably the HTML 5 Draft Spec Event Loop, but it doesn't seem to specify anything about the order of form events.

All that said, I'd probably avoid on anything that super-explicitly required that change fired before submit. I assume it would be for validation. I would probably have the submit function call the validation function itself without calling change.

samanime
  • 25,408
  • 15
  • 90
  • 139