Skip to content
Advertisement

Why does hitting enter in a textbox trigger a click-event in another button

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement