最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript why onClick getting called by enter-key - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Oct 16, 2015 at 9:26 MihawkMihawk 8353 gold badges14 silver badges33 bronze badges 2
  • 1 We'd need a lot more information to work with to be able to usefully answer this question. – T.J. Crowder Commented Oct 16, 2015 at 9:28
  • Please post your relevant HTML. In particular, is the button a submit button? Also, how do you know a button click is being triggered, since you are calling the same function in both cases? – Amadan Commented Oct 16, 2015 at 9:29
Add a ment  | 

2 Answers 2

Reset to default 7

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>

You will e across this situation if you have a <button> element inside your form(if the purpose of the button is to not to submit the form) without specifying the type as type="button". Please refer to this discussion for more information.

发布评论

评论列表(0)

  1. 暂无评论