Creating Tag Input Field in JavaScript


Tag input in JavaScript is a user interface component that allows users to add tags to a form input field. A tag is a small piece of text that describes the content or category of the input. Tag inputs are commonly used in web applications that require users to add multiple tags to an item, such as blog posts, images, or products.

To create a tag input field in JavaScript, you can use a combination of HTML, CSS, and JavaScript. The HTML code defines the structure of the input field, and the CSS styles the appearance of the field. The JavaScript code handles the user interaction and adds the tags to the input field.

One common feature of tag inputs is the autocomplete functionality. This feature suggests tags based on the user's input, making it easier for the user to select tags that are already in use or popular. Autocomplete is implemented using JavaScript and the DOM manipulation techniques.

Once the user adds a tag to the input field, it can be displayed as a small chip or button within the field. The user can remove the tag by clicking on the chip or button, which triggers an event that removes the tag from the input field.

Source Code

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script type="module" src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/ionicons@5.5.2/dist/ionicons/ionicons.js"></script>

    <link rel="stylesheet" href="css/style.css" />
  </head>
  <body>
    <div class="container">
      <div class="tag-container">
        <!-- <div class="tag">
          <span>HTML</span>
          <ion-icon name="close-circle-outline"></ion-icon>
        </div>
        <div class="tag">
          <span>CSS</span>
          <ion-icon name="close-circle-outline"></ion-icon>
        </div>
        <div class="tag">
          <span>JavaScript</span>
          <ion-icon name="close-circle-outline"></ion-icon>
        </div> -->
        <input type="text" />
      </div>

      <div class="icons">
        <ion-icon name="copy-outline" id="copy"></ion-icon>
        <ion-icon name="close-outline" id="removeAll"></ion-icon>
      </div>
    </div>
    <script src="js/script.js"></script>
  </body>
</html>

css/style.css

@import url("https://fonts.googleapis.com/css2?family=Poppins:wght@100;300;400;500;600;700;800&display=swap");

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: "Poppins", sans-serif;
}

body {
  width: 100vw;
  height: 100vh;
  display: grid;
  place-items: center;
}
.container {
  background-color: #fff;
  width: 80%;
  display: flex;
  padding: 10px;
  border: 1px solid #aaa;
  border-radius: 4px;
}
.icons ion-icon {
  padding: 10px;
  cursor: pointer;
}
.tag-container {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
}
.tag {
  padding: 5px;
  border: 1px solid #aaa;
  margin: 5px;
  display: flex;
  align-items: center;
  background-color: #f2f2f2;
  border-radius: 15px;
}

.tag ion-icon {
  margin-left: 5px;
  cursor: pointer;
}
.tag-container input {
  flex: 1;
  font-size: 16px;
  padding: 5px;
  outline: none;
  border: 0;
}

js/script.js

const tagContainer = document.querySelector(".tag-container");
const input = document.querySelector(".tag-container input");
const btnRemoveAll = document.querySelector("#removeAll");
const btnCopy = document.querySelector("#copy");

let tags = [];

/*
<div class="tag">
  <span>HTML</span>
  <ion-icon name="close-circle-outline"></ion-icon>
</div>
*/
function createTag(tag) {
  const div = document.createElement("div");
  div.setAttribute("class", "tag");
  const span = document.createElement("span");
  span.innerHTML = tag;
  const icon = document.createElement("ion-icon");
  icon.setAttribute("name", "close-circle-outline");
  icon.setAttribute("data-item", tag);
  div.appendChild(span);
  div.appendChild(icon);
  return div;
}

function reset() {
  const tagElements = document.querySelectorAll(".tag");
  tagElements.forEach((tag) => {
    tag.parentElement.removeChild(tag);
  });
}

btnRemoveAll.addEventListener("click", function () {
  tags = [];
  reset();
});

function addTags() {
  reset();
  tags
    .slice()
    .reverse()
    .forEach((tag) => {
      tagContainer.prepend(createTag(tag));
    });
}

input.addEventListener("keyup", function (event) {
  if (event.key == "Enter") {
    const data = input.value.trim();
    if (data.includes(",")) {
      const list_of_tags = data.split(",");
      // list_of_tags.forEach((element) => {
      //   console.log(createTag(element));
      // });
      tags.push(...list_of_tags);
    } else {
      // console.log(createTag(data));
      tags.push(data);
    }
    tags = [...new Set(tags)];
    input.value = "";
    addTags();
  }
});
document.addEventListener("click", function (e) {
  if (e.target.tagName == "ION-ICON") {
    const data = e.target.getAttribute("data-item");
    const filterTags = tags.filter((tag) => {
      return tag != data;
    });
    tags = filterTags;
    addTags();
  }
});

btnCopy.addEventListener("click", function () {
  if (tags.length) {
    navigator.clipboard
      .writeText(tags.toString())
      .then(() => {
        alert("Tag Copied to Clipboard !");
      })
      .catch((error) => {
        console.error("Failed to Copy", error);
      });
  }
});

This JavaScript code creates a tag input field in a web application. The code defines a function called createTag that generates a new tag element with a span and an ion-icon element inside a div container. The span element displays the tag text, and the ion-icon element provides a clickable icon that allows users to remove the tag.

The code uses several event listeners to capture user input and interaction. When the user enters a tag in the input field and presses the "Enter" key, the code adds the tag to an array called tags and clears the input field. If the input contains multiple tags separated by commas, the code splits the input into separate tags and adds them individually to the tags array.

The code also adds an event listener to the document that listens for clicks on the ion-icon elements. When a user clicks on an ion-icon, the code identifies the associated tag and removes it from the tags array.

The reset function is called whenever tags are added or removed. It removes all existing tag elements from the tag container and then calls the addTags function to regenerate the tag elements based on the current contents of the tags array.

Finally, the code adds event listeners to two buttons, one for copying the contents of the tags array to the clipboard and one for removing all tags from the tags array.

Overall, this code provides a functional tag input field that allows users to add and remove tags to an array in real-time, making it a useful tool for web applications that require a tagging system.

Output

Tag Input

Live Preview


Overall, tag input in JavaScript is a useful tool for creating a tagging system that improves the user experience and organization of data in web applications.

List of Programs


JS Practical Questions & Answers


JS Practical Project