JSFiddle - React, Tailwind, and code Playground
HTML
<div class="tag_wrap">
<div class="hd">Add and remove tags</div>
<ul id="tags_list" class="tags_list"></ul>
<input type="text" id="tag_txt" placeholder="Type and enter ...">
</div>
CSS
body {
font-family: 'Helvetica';
font-size: 13px;
background: #ddd;
}
.tag_wrap {
width: 500px;
padding: 15px 15px 10px 15px;
border-radius: 7px;
border: 1px solid #ccc;
background: #fff;
margin: 50px;
}
.tag_wrap .hd {
margin-bottom: 15px;
font-size: 17px;
}
.tag_wrap input {
border: 0px;
background: none;
margin-bottom: 5px;
display: inline-block;
outline: 0;
}
ul.tags_list {
list-style: none;
margin: 0px;
padding: 0px;
display: inline;
}
ul.tags_list li {
display: inline-block;
background: #4769e7;
color: #fff;
padding: 9px 12px 9px 17px;
border-radius: 20px;
margin-right: 5px;
margin-bottom: 5px;
}
ul.tags_list li .remove {
color: #fff;
text-decoration: none;
margin-left: 8px;
font-size: 10px;
background: #2c23af;
width: 20px;
height: 20px;
border-radius: 50%;
display: inline-flex;
text-align: center;
align-items: center;
justify-content: center;
cursor: pointer;
opacity: .7;
}
ul.tags_list li .remove:hover {
opacity: 1;
}
JavaScript
var tag_txt = document.getElementById('tag_txt');
var tags_list = document.getElementById('tags_list');
var tag_items = ['Devsheet', 'Lotis'];
tag_txt.addEventListener('keypress', function(e) {
if (e.key === 'Enter') {
let value = tag_txt.value;
if (value !== '') {
if (tag_items.indexOf(value) >= 0) {
alert('Tag already added');
} else {
tag_items.push(value);
append_tags();
tag_txt.value = '';
tag_txt.focus();
}
} else {
alert('Please enter a tag Name');
}
}
});
function append_tags() {
tags_list.innerHTML = '';
tag_items.map((item, index) => {
tags_list.innerHTML += `<li><span>${item}</span><span class="remove" onclick="javascript: remove(${index})">X</span></li>`;
});
}
function remove(i) {
tag_items = tag_items.filter(item => tag_items.indexOf(item) != i);
append_tags();
}
window.onload = function() {
append_tags();
tag_txt.focus();
}