Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67469

How to detect ENTER key press on an input field before the form is submitted?

$
0
0

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.


Viewing all articles
Browse latest Browse all 67469

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>