Skip to content

Instantly share code, notes, and snippets.

@dotja
Created October 30, 2020 22:44
Show Gist options
  • Save dotja/4fae22d29231a45e1eb53d4bfd686efb to your computer and use it in GitHub Desktop.
Save dotja/4fae22d29231a45e1eb53d4bfd686efb to your computer and use it in GitHub Desktop.
Implement the comma-separated tags input box with Javascript.
<!DOCTYPE html>
<html>
<head>
<title>Tags</title>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
</head>
<body>
<style type="text/css">
.container {
margin-top: 50px;
}
#remove:hover {
cursor: pointer;
}
#tags {
margin-top: 10px;
}
</style>
<div class="container">
<div class="col-sm-6">
<input onkeyup="parse();" type="text" id="tags_input" placeholder="comma-separated tags" maxlength="100" class="form-control">
</div>
<div class="col-sm-6" id="tags">
</div>
</div>
<script type="text/javascript">
function parse() {
var tag_input = document.getElementById("tags_input");
var tags = document.getElementById("tags");
//
var input_val = tag_input.value.trim();
var no_comma_val = input_val.replace(/,/g, "");
//
if (input_val.slice(-1) === "," && no_comma_val.length > 0) {
var new_tag = compile_tag(no_comma_val);
tags.appendChild(new_tag);
tag_input.value = "";
}
}
function compile_tag(tag_content) {
var tag = document.createElement("h5");
//
var text = document.createElement("span");
text.setAttribute("class", "badge badge-success");
text.innerHTML = tag_content;
//
var remove = document.createElement("i");
remove.setAttribute("class", "fa fa-remove");
remove.setAttribute("id", "remove");
remove.onclick = function() {this.parentNode.remove();};
//
tag.appendChild(remove);
tag.appendChild(text);
//
return tag;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment