How to disable autocomplete for email input in HTML forms

Recently I was making a simple web form to allow admins of a site to create accounts for new users. The admin enters the email address of the new user. When the form is submitted, a random password is generated and emailed to the user. (This is for privacy/security: it prevents the admin from knowing another user’s password.) However, the admin needs to enter their own password when submitting the form. In other words, the email address and password fields in the form are for two different accounts. The problem is that the browser always prompts the user to autofill their email address and password. Worse, if the user fills in the new email address, then autocompletes their password afterwards, the browser overwrites the new user’s email address with the admin user’s email address. This makes for a very buggy and confusing user experience.

It took a while of head scratching, research and testing to find a way around this. The key turned out to be to use the readonly attribute on the email address, based on this StackOverflow post.

Here’s a minimal example. It uses jQuery, but you could fairly easily achieve something similar with vanilla JavaScript.

<!doctype html>
<html lang='en'>
  <head>
    <title>Demo registration form</title>
    <meta charset='utf-8' />

    <script src='https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js'></script>
  </head>
  <body>
    <h1>Add a new user</h1>
    <form action='.' autocomplete='off' method='post'>
      <label for='new_email'>Email address of <strong>NEW</strong> user</label><br />
      <input type='email' autocomplete='off' name='email' /><br /><br />

      <label for='password'>Password of <strong>CURRENT</strong> user</label><br />
      <input type='password' autocomplete='current-password' />
    </form>
    <script>
    //<![CDATA[
      $( function() {
        $( 'input[name=email]' ).on( 'blur', function() {
          $( this ).prop( 'readonly', true );
        } );
        $( 'input[name=email]' ).on( 'focus', function() {
          $( this ).prop( 'readonly', false );
        } );
      } );
    //]]>
    </script>
  </body>
</html>

Add new comment

CAPTCHA