javascripthtmlforms

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.


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>