Input field for Tags separated by comma

Something similar like Stack Overflow does:

enter image description here

  • Allows alphanumeric and +-.# (and trims whitespaces!)
  • Convert to lowercase
  • Create automatically the Tag Box on focusOut Enter , (add more delimited by | pipe)
  • Delete Tag on click
jQuery($ => { // DOM ready and $ alias in scope.

  // TAGS BOX
  $("#tags input").on({
    focusout() {
      var txt = this.value.replace(/[^a-z0-9\+\-\.\#]/ig,''); // allowed characters
      if(txt) $("<span/>", {text:txt.toLowerCase(), insertBefore:this});
      this.value = "";
    },
    keyup(ev) {
      if(/(,|Enter)/.test(ev.key)) $(this).focusout(); 
    }
  });
  $("#tags").on("click", "span", function() {
    $(this).remove(); 
  });
  
});
#tags{
  float:left;
  border:1px solid #ccc;
  padding:5px;
  font-family:Arial;
}
#tags > span{
  cursor:pointer;
  display:block;
  float:left;
  color:#fff;
  background:#789;
  padding:5px;
  padding-right:25px;
  margin:4px;
}
#tags > span:hover{
  opacity:0.7;
}
#tags > span:after{
 position:absolute;
 content:"×";
 border:1px solid;
 padding:2px 5px;
 margin-left:3px;
 font-size:11px;
}
#tags > input{
  background:#eee;
  border:0;
  margin:4px;
  padding:7px;
  width:auto;
}
<div id="tags">
  <span>php</span>
  <span>c++</span>
  <span>jquery</span>
  <input type="text" value="" placeholder="Add a tag" />
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Leave a Comment