Please check the following code:
https://codepen.io/tkpop777/pen/vYYVBOe
HTML:
<form>
<input type="text" value="text field 1" />
<br />
<input type="text" value="text field 2" id="textfield2" />
<br />
<button>Submit</button>
</form>
JS:
document.querySelector('#textfield2').onkeyup = (e) => {
e.preventDefault();
if (e.keyCode == 13) {
alert('enter key')
}
}
document.querySelector('form').onsubmit = (e) => {
e.preventDefault();
alert('form submitted');
}
If you are on the second input field and hit the ENTER key you will receive the "form submitted" alert and never the "enter key" alert. Moving the input field out of the form tags gives you the "enter key" alert. How can I receive that alert even when that field is within the form tags. Basically it should fire first before the form submitted alert.