Reputation:
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.
Upvotes: 2
Views: 65
Reputation: 872
You don't prevent your button from submitting the form, which is why this is happening. By default when you hit enter, the button in your form is triggered and the form gets submitted.
just add this
document.querySelector('button').onclick = (e) => {
e.preventDefault();
}
Upvotes: 0
Reputation: 1072
Check onkeydown
instead of onkeyup
document.querySelector('#textfield2').onkeydown = (e) => {
if (e.keyCode == 13) {
alert('enter key')
}
}
document.querySelector('form').onsubmit = (e) => {
e.preventDefault();
alert('form submitted');
}
Note: I also removed e.preventDefault()
from the onkeydown
event so that the form is actually submitted afterwards.
Updated codepen: https://codepen.io/tkpop777/pen/vYYVBOe
Upvotes: 3
Reputation: 918
Your onsubmit
event takes precedence because you are not listening on for a keydown
event but for a keyup
.
This should do what you need:
document.querySelector('#textfield2').onkeydown = (e) => {
e.preventDefault();
if (e.keyCode == 13) {
alert('enter key')
}
}
Upvotes: 0