1

Consider This:

  const button = document.querySelector('#button');

  button.addEventListener('click', e => {
    e.preventDefault();
    alert("why did this happen?");
  });
<form>
<label for="input">L<input type="text" id="input" name="input"></label>
<button id="button">B</button>
</form>

Go into the textbox and hit Enter. You see an alert, which indicates that the click-event of the button got triggered. But why did this happen? I can understand, that the enter event bubbles up to the form and triggers a submit. preventDefault prevents this. But what does the button have to do with it?

Paflow
  • 2,030
  • 3
  • 30
  • 50
  • Instead of the button try the form as the listener for the 'submit' event rather than the 'click' event. ex `document.forms[0].addEventListener('submit', eventHandler)` – zer00ne Jun 08 '21 at 20:11

1 Answers1

3

Pressing Enter in a single text box in a form triggers form submission by way of simulating a click on the default submit button.

I think the historical motivation is so that when people add a click event to the submit event without considering that people might expect Enter to submit a form it still works.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • I even knew that but it's quite surprising that a button-element which is not of type `submit` can be considered as standard-submit button. I hope, I can find some documentation how exactly this behavior is defined to work with it. – Paflow Jun 09 '21 at 07:39
  • Found it... https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#default-button – Paflow Jun 09 '21 at 07:48
  • @Paflow — It is of type `submit`, that's the default value of the `type` attribute – Quentin Jun 09 '21 at 08:00