Skip to content

Instantly share code, notes, and snippets.

@mckabi
Last active August 21, 2019 02:56
Show Gist options
  • Save mckabi/7af465310b3066a679fe9a5a80a0fe51 to your computer and use it in GitHub Desktop.
Save mckabi/7af465310b3066a679fe9a5a80a0fe51 to your computer and use it in GitHub Desktop.
document.querySelector('input[type=email]').addEventListener('keyup', event => {
const element = event.target;
const valueParts = element.value.split('@');
if (element.getAttribute('list') && document.getElementById(element.getAttribute('list'))) {
document.getElementById(element.getAttribute('list')).remove();
}
if (valueParts.length > 1 && valueParts[0] && valueParts[1]) {
const suggestionsId = (element.id || element.name) + 'Suggestion';
const suggestions = makeDatalist(suggestionsId, valueParts[0], valueParts[1]);
element.parentNode.insertBefore(suggestions, element.nextSibling);
element.setAttribute('list', suggestionsId);
}
});
const makeDatalist = (elementId, emailId) => {
const suggestDomains = [
'naver.com',
'hanmail.net',
'daum.net',
'gmail.com',
'nate.com'
];
const defaultOption = document.createElement('option');
defaultOption.setAttribute('value', emailId + '@');
defaultOption.innerText = `${emailId}@...`;
const element = document.createElement('datalist');
element.setAttribute('id', elementId);
suggestDomains.forEach(domain => {
const option = document.createElement('option');
const emailAddress = `${emailId}@${domain}`;
option.setAttribute('value', emailAddress);
option.innerText = emailAddress;
element.appendChild(option);
});
element.appendChild(defaultOption);
return element;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment