If, in a registration form, it is desired to extract the username from the e-mail address, in order to simplify data entry, the SPLIT function can be used. This function generating a table of values (username, domain), the first value ([0]) will be chosen, the e-mail address domain being obviously the value [1].
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<form> <input type="email" name="email" id="email" /> <input type="text" id="username" disabled style="border:none;" /> </form> <script> var email = document.getElementById('email'); var username = document.getElementById('username'); email.onchange = function() { var mail_val = email.value; let id_email = mail_val.split('@')[0] username.value = id_email; } </script> |
If you want the username to be displayed in real time (as letters are entered), change the ONCHANGE event to ONKEYUP. The username will appear only after the letter from the argument of the SPLIT function is entered; to prevent the expression “undefined” from appearing until the “@” symbol is entered, the code of that function can be adjusted a bit, as shown below.
1 2 3 4 5 6 7 8 9 |
email.onkeyup = function() { var mail_val = email.value; let id_email = mail_val.split('@')[0] if (id_email.length>0) { username.value = id_email; } } |
If you want to display the username in an element other than input-text (for example, span), change the line username.value = id_email; with username.innerHTML = id_email;