Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

308
Views
Javascript: Invoke function directly or dispatch event?

Where we have js code that submits a form instead of just submitting the form like:

form.submit();

Should we instead dispatch a (bubbling, cancelable) event in order to allow other potential js event listeners the chance to handle the form submission:

form.dispatchEvent(new Event('submit', {bubbles: true, cancelable: true}));

It seems like this allows our code to play more nicely with others. If this is true, why isn't this pattern pushed more?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

HTMLFormElement.requestSubmit() to the rescue!

In most cases in which a form is to be submitted programmatically via JavaScript, it's wise to use requestSubmit() rather than submit(). Doing so ensures submit handlers will have a chance to handle the submit event. Use submit() only when you want to explicitly submit the form ignoring any registered submit event listeners and form validation.

I was simply not aware of this newer form method.

See https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/submit

The HTMLFormElement.submit() method submits a given <form>.

This method is similar, but not identical to, activating a form's submit <button>. When invoking this method directly, however:

  • No submit event is raised. In particular, the form's onsubmit event handler is not run.
  • Constraint validation is not triggered.

The HTMLFormElement.requestSubmit() method is identical to activating a form's submit <button> and does not have these differences.

And usage notes from https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/requestSubmit

The obvious question is: Why does this method [requestSubmit()] exist, when we've had the submit() method since the dawn of time?

The answer is simple. submit() submits the form, but that's all it does. requestSubmit(), on the other hand, acts as if a submit button were clicked. The form's content is validated, and the form is submitted only if validation succeeds. Once the form has been submitted, the submit event is sent back to the form object.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!