How to enter multiple email inputs in one field?

1.2k views Asked by At

I would like to create an input field that accept multiple email addresses (for example to send an invitation). How can I achieve this without the help of jQuery or an external plugin or package?

I used to rely on bootstrap-tagsinput but I want to get rid of it, but I have no idea how to achieve the same thing without it.

1

There are 1 answers

0
Diego D On

This solution is quite a carbon copy of how the bootstrap tags input behaves but uses vanilla js only and some style rules.

It captures the click event on the container to create a text input inside that when will loose focus, will create a .tag span inside its parent with its original value (unless that value is empty spaces).

You may also change that condition so that it will create the tag only if the typed text matches a regular expression describing a valid email address.

const emailInput = document.getElementById('emailInputContainer');

//creates a tag element with the given text
function createTag(text){  
  const tag = document.createElement('span');
  tag.classList.add('tag');
  tag.innerText = text;
  
  const remove = document.createElement('span');  
  remove.classList.add('remove');  
  tag.append(remove);
  
  remove.addEventListener('click', (event)=>{
    event.currentTarget.parentElement.remove();
  });
  
  return tag;
}

//creates and returns an input element
function createNewInput(){
  const newInput = document.createElement('input');
  newInput.classList.add('tempinput');
  newInput.addEventListener('focusout', (event)=>{  
    const target = event.currentTarget;  
    if(target.value.trim().length > 0){
      const tag = createTag(target.value);
      target.parentElement.append(tag);
    }          
    target.remove();
  });  
  
  return newInput;
}

//adds the click event listener to the input container
emailInput.addEventListener('click', (event)=>{  
  const target = event.currentTarget;
  const newInput = createNewInput();  
  target.append(newInput);
  newInput.focus();
});
body{
  font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}

#emailInputContainer{
  border: solid 1px;
  background-color: #fff;
  border: 1px solid #ccc;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
  display: inline-block;
  padding: 4px 6px;
  color: #555;
  vertical-align: middle;
  border-radius: 4px;  
  line-height: 22px;
  cursor: text;
  width: 100%;
  height: 1.5em;
}

.tag{  
  padding: 2px 5px;
  margin-right: 5px;
  background: #5bc0de;
  color: white;
  display: inline;
  padding: .2em .6em .3em;
  font-size: 75%;
  font-weight: 700;
  line-height: 1;
  color: #fff;
  text-align: center;
  white-space: nowrap;
  vertical-align: baseline;
  border-radius: .25em;
}

.tempinput{
  border: none;
  outline: none;  
}

.tag > .remove{
  margin-left: 8px;
  cursor: pointer;
}

.tag > .remove::after{
  content: "x";
  padding: 0px 0px;
}
<div id="emailInputContainer" tabindex="0">
</div>