-2

I am coding a webpage that has a form with one field where a user types in a set of numbers then press a button that says 'Run' to run the code, the problem is when you press the 'enter' key instead of the 'Run' button it doesn't do anything. It is suppose to run a javascript method called 'calculate()'.

I tried looking for a method called 'onEnter' or 'onSubmit' but couldn't find any.

Dan
  • 1,100
  • 2
  • 13
  • 36
  • if the field is a textarea, this is a duplicate https://stackoverflow.com/questions/2099661/enter-key-in-textarea there is no such method onEnter, onSubmit is a form event not text input event, you need to read more about the JS API, you just can't call random functions and expect to work. – Pablo Pazos Sep 19 '18 at 05:08
  • Have you tried `keypress` event of button and then handle enter key code which is 13? – Arun Kumar Sep 19 '18 at 05:09
  • I can't see any code here. Perhaps you can add some? – dcangulo Sep 19 '18 at 05:10
  • `onSubmit` is available on the `
    ` tag. And you can still `preventDefault` behaviour when submitting.
    – Thomas Sep 19 '18 at 05:33

1 Answers1

2

You can attach a listener on the keypress in the body / some specific element. The key code for enter is 13, so you can listen to that.

let element = document.getElementById('#some-element');

element.addEventListener('keydown', (e) => {
  e.preventDefault();
  if (e.keyCode === 13) {
    calculate();
  }
});
Sivcan Singh
  • 1,775
  • 11
  • 15