What are submit forms in JavaScript?

You can manually submit forms through JavaScript using the submit() and requestSubmit() methods.

Submitting forms through JavaScript gives you more control. You can prevent default behaviors, validate the form, or process inputs in JavaScript before the form is sent to the server.

svg viewer

Syntax

  • HTMLFormElement.submit()

The submit() method does not accept any parameters and does not return anything.

Note: Invoking submit() does not raise a submit event; the form’s onsubmit handler is not run.

  • HTMLFormElement.requestSubmit(submitter)

    • submitter: (Optional) The submit button used to handle form submission. If not provided, the form element itself is used as submitter.

The requestSubmit() method is used when you want to activate the form’s submit <button> or raise the form’s onsubmit handler.

Example

Let’s try submitting a form using an image.

Using submit()

Notice how the form’s onsubmit handler is not called.

Console
submit( )

Using requestSubmit()

The form’s onsubmit handler is called. Here we use it to prevent page reload on form submission.

Console
requestSubmit( )

For more details on both methods, you can check out the official docs here and here.

Copyright ©2024 Educative, Inc. All rights reserved