Consider This:
JavaScript
x
6
1
const button = document.querySelector('#button');
2
3
button.addEventListener('click', e => {
4
e.preventDefault();
5
alert("why did this happen?");
6
});
JavaScript
1
4
1
<form>
2
<label for="input">L<input type="text" id="input" name="input"></label>
3
<button id="button">B</button>
4
</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.