Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 432
Avery235 Avatar asked Feb 14 '26 03:02

Avery235


2 Answers

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.

like image 102
Draconis Avatar answered Feb 15 '26 15:02

Draconis


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

like image 26
Chris Avatar answered Feb 15 '26 15:02

Chris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!