Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to trigger input's blur event when submitting form by pressing enter

I have the following simple HTML form:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
      function onBlur() {
        console.log("blur  event");
      }
      function onSubmit(e) {
        console.log("submit  event", e);
        e.preventDefault();
      }
    </script>
  </head>
  <body>
    <form onSubmit="onSubmit(event)">
      <input name="code" onBlur="onBlur()" />
      <button>Submit</button>
    </form>
  </body>
</html>

When submitting the form by pressing the enter key, the input does not lose focus, and the blur event is never called.

Is there a way to disable this behavior? I can query for the input and call the blur function, but I am wondering if there is a cleaner way to do it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I can query for the input and call the blur function, but I am wondering if there is a cleaner way to do it.

Yes, you can call blur() on the document.activeElement:

document.activeElement.blur()

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script>
      function onBlur() {
        console.log("blur  event");
      }
      function onSubmit(e) {
        e.preventDefault();
        document.activeElement.blur()
        console.log("submit  event");
      }
    </script>
  </head>
  <body>
    <form onSubmit="onSubmit(event)">
      <input name="code" onBlur="onBlur()" />
      <button>Submit</button>
    </form>
  </body>
</html>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading