0

Currently, a user has to manually click on the "Login" button in the form, for it to trigger the "onSubmit".

I've tried implementing a hacky way to do it on enter, but I'm wondering if there is a better way to do this?

  useEffect(() => {
    const emailField = document.getElementById('username');
    const passwordField = document.getElementById('password');

    emailField.addEventListener('keyup', e => {
      const { keyCode } = e;

      if (keyCode === 13) {
        e.preventDefault();
        document.getElementById('login').click();
      }
    });

    passwordField.addEventListener('keyup', e => {
      const { keyCode } = e;

      if (keyCode === 13) {
        e.preventDefault();
        document.getElementById('login').click();
      }
    });
  }, []);
Mike K
  • 7,621
  • 14
  • 60
  • 120
  • You tagged this `reactjs` but there's no React code in your question – slebetman Dec 12 '19 at 08:05
  • `useEffect` is a React hook – Mike K Dec 12 '19 at 08:06
  • @slebetman `useEffect` is a React hook, so yes it is React code – Jayce444 Dec 12 '19 at 08:06
  • I don't know why this question was closed. @deceze closed it as a duplicate for [this](https://stackoverflow.com/questions/8082846/form-submit-execute-javascript-best-practice) question -- which is not even relevant to mine. – Mike K Dec 12 '19 at 08:07
  • Oh man you're mixing React and DOM. This is going to be nasty. – slebetman Dec 12 '19 at 08:07
  • 2
    Can you please either criticize the format of my question or post an answer? I'm not going to argue with you about how you're wrong about "mixing React and DOM" -- something everyone who uses React does. – Mike K Dec 12 '19 at 08:09
  • 1
    So [this](https://stackoverflow.com/a/39442477/476) doesn't work for you? If not: why? Why your current approach at all? – deceze Dec 12 '19 at 08:12
  • Because I'm using React Admin, and `e.target.value` always prints the previous state (ie, I'll never catch the "enter"), and `e.keyCode` always prints `0` – Mike K Dec 12 '19 at 08:19
  • 1
    You should clarify all these things as part of the question. – deceze Dec 12 '19 at 08:21
  • @slebetman using DOM in react is totaly valid. But there is better choice in this particular usecase imho. Just wrap your inputs to some parent and bind onKeyDown on that parent. Here is [codesandbox](https://codesandbox.io/s/elastic-cartwright-r5qhi) – Pavel Kratochvil Dec 12 '19 at 08:40

1 Answers1

0

After seeing the blank array you passed as a parameter in the useEffect(), seems like you want to submit only once at the page load time. So, I will suggest you to go for -

function submit() {
//do submission here
}
function init(){
  document.getElementById('form').onsubmit = submit;
}
window.onload = init;
Rajat Sharma
  • 65
  • 1
  • 8