How to show a default domain name in an email address input field?

Viewed 2329

I have a login form for a website that requires email address and password. Most users have the same email address domain, but a few users have email addresses from a different domain.

Is there a way to automatically use a default domain name in the email address input field, while still allowing the user to type in a different domain name?

For example, if | is the cursor, the input would look something like this while typing:

|@defaultreallylongdomain.com (user hasn't typed anything yet)

b|@defaultreallylongdomain.com

bo|@defaultreallylongdomain.com

bob|@defaultreallylongdomain.com

bob@|defaultreallylongdomain.com

bob@g|

.

. (user keeps typing)

.

bob@gmail.com|

The default domain shows up to the right of the cursor, until the user starts typing a domain name that doesn't match the default domain.

Any ideas on how to accomplish this?

2 Answers

Use selectionStart

Here is example:

html

<input id='email' type='text'>

js

const input = document.getElementById('email');
const defaultEmail = '@gmail.com';
input.value = defaultEmail;

function handleInput() {
    const val = input.value;
    const sel = input.selectionStart;
    if (val.length - defaultEmail.length < sel) {
        input.value = val.slice(0, sel)
        input.removeEventListener('input', handleInput);
        input.removeEventListener('focus', handleInput);
        input.removeEventListener('click', handleInput);
    }
}

input.addEventListener('input', handleInput);
input.addEventListener('focus', handleInput);
input.addEventListener('click', handleInput);

Live demo

This is pretty inelegant and basic example, but you could build on it. Essentially, you could;

  1. Pre-fill the input with the default domain
  2. Keep track of the currently typed email
  3. Force the user to the start of the input when clicked
  4. If the user types a "@" character, you know they want a different domain
  5. Replace input value with what the user has typed so far

Like this;

$(document).ready(function(){
  let defaultDomain = 'exampledomain.net'; // use this to remove later
  let input = $("#testInput");
  let typed = ""; // keep track of what the user has typed
  
  // put cursor at start when clicked
  input.click(function(){
   $(this).get(0).setSelectionRange(0,0);
  })
  
  input.keydown(function(e){
    // @ is keycode 192
    if(e.keyCode === 192){
      // the user has typed @ and you can assume that they want a different domain
      input.val(typed.substring(0, typed.length - 1));
    }else{
        // store the email the user has typed so far, minnus default domain
        typed = input.val().replace(defaultDomain, '');
    }
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="testInput" value="@exampledomain.net">

Related