Avery235
Avery235

Reputation: 5306

form onSubmit vs onClick

<form>
  <input />
  <button
    onClick={e => {
      e.preventDefault();
      alert("clicked");
    }}
  >
    click
  </button>
</form>

Edit zrzz6pj7kx

If I move the onClick handler to form's onSubmit, I will get the exact same behavior.

Most answers I googled suggested that the difference is onClick will not react to submitting form via return key press but that's not true as seen in the codesandbox example.

When will they behave differently, apart from when dealing with DOM manipulation/event simulation?

Upvotes: 3

Views: 7239

Answers (2)

Chris
Chris

Reputation: 759

The other main difference is the target for the event.

Note that the submit event fires on the <form> element itself, and not on any <button> or <input type="submit"> inside it. (Forms are submitted, not buttons.)

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

Upvotes: 3

Draconis
Draconis

Reputation: 3461

Fundamentally, this is up to the browser. Some browsers might call a submit button's onClick when the form is submitted by pressing the return key, but the standard doesn't mandate this. Others might only call onClick when return is pressed if the submit button is selected. Others might not fire it unless the button is manually clicked.

If you want the best portability, use onSubmit for what it's designed for: to detect form submission.

Upvotes: 8

Related Questions