Skip to content
Advertisement

Javascript why onClick getting called by enter-key

I’ve got a button with the onClick-event and a textfield with onKeyDown-event.

Button: onclick="myFunc(3)"
Textfield: onKeyDown="if(event.keyCode==13) myFunc(3);"

Somehow the button is getting called if I press the enter-key and I don’t know why.

Advertisement

Answer

When you press Enter in a text field, you trigger a form submission and browsers simulate clicking on the first submit button of the form.

You can avoid this by preventing the default action of the keypress (not keydown) event.

var s = document.querySelector('[type=submit]');
var t = document.querySelector('[type=text]');
var f = document.querySelector('form');

t.addEventListener('keydown', function(event) {
  if (event.keyCode == 13) {
    alert("enter pressed")
  }
});

t.addEventListener('keypress', function(event) {
  if (event.keyCode == 13) {
    event.preventDefault();
  }
});
<form action="/">
  <input type="text">
  <input type="submit">
</form>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement