TAGS input

simple version add tag on input filds, use comma as separator to make tags...

by slawe

HTML

<div id="tags">
    <input type="text" id="input-tags" value="nula,jedan" placeholder="Add a tag">
    <input type="hidden" id="hidden-tags">
</div>

CSS

#tags{
  float:left;
  border:1px solid #ccc;
  padding:5px;
  font-family:Arial;
}
#tags span.tag{
  cursor:pointer;
  display:block;
  float:left;
  padding:5px;
  padding-right:25px;
  margin:4px;
  color:#ffffff;
  background:#0082FE;
}
#tags span.tag:hover{
  opacity:0.7;
}
#tags span.tag:after{
 position:absolute;
 content:"x";
 border:1px solid;
 padding:0 4px;
 margin:3px 0 10px 5px;
 font-size:10px;
}
#tags input{
  background:#eee;
  border:0;
  margin:4px;
  padding:7px;
  width:auto;
}

JavaScript

let tags = {

	wrapper: $('#tags'),
	input: $('#input-tags'),
  hidden: $('#hidden-tags'),
	
  init: function() {
  	let that = this,
    		field = that.input;
  	that.makeTag(field);
    field.on('keyup', function(e) {
    	if(/(188|13)/.test(e.which)) {
    		that.makeTag($(this), false);
      }
    });
  },
  
  clear: function(el, commaAllowed = true) {
  	let reg = commaAllowed ? /[^a-z0-9,]/gi : /[^a-z0-9]/gi;
  	let text = el.val().replace(reg,'');
    return text.toLowerCase();
  },
  
  makeTag: function(el, commaAllowed) {
  	let val = this.clear(el, commaAllowed);
  	if(val) {
    	let arr = val.split(',');
      for(let i in arr) {
  			el.before('<span class="tag">'+arr[i]+'</span>');
      }
    }
    el.val('');
    this.removeTag();
    this.update();
  },
  
  removeTag: function() {
  	let that = this;
  	this.wrapper.on('click', '.tag', function() {
    	$(this).remove();
    	that.update();
    });
  },
  
  update: function() {
  	let array = $.map($('.tag'), function(e, i) {
    	return e.innerHTML;
    });
    this.hidden.val(array.join(','));
  },
};

$(document).ready(function() {
    tags.init();
});