How to create a dynamic tag input field with jQuery



Image not found!!

Creating a dynamic tag input field with jQuery involves handling user input, adding tags dynamically, and providing a smooth user experience. Here's a simple example to get you started:

HTML:

html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dynamic Tag Input</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="tag-container"> <input type="text" id="tag-input" placeholder="Add tags"> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script src="script.js"></script> </body> </html>

CSS (styles.css):

css
.tag-container { display: flex; flex-wrap: wrap; border: 1px solid #ccc; padding: 5px; } .tag { background-color: #3498db; color: #fff; padding: 5px 10px; margin: 5px; border-radius: 3px; cursor: pointer; }

JavaScript (script.js):

js
$(document).ready(function() { // Array to store tags var tags = []; // Function to add a tag function addTag(tag) { // Check if the tag already exists if (tags.indexOf(tag) === -1) { tags.push(tag); // Update the tag display updateTags(); } } // Function to remove a tag function removeTag(tag) { tags = tags.filter(function(item) { return item !== tag; }); // Update the tag display updateTags(); } // Function to update the tag display function updateTags() { var tagContainer = $(".tag-container"); tagContainer.empty(); // Add each tag to the container tags.forEach(function(tag) { var tagElement = $("<div class='tag'>" + tag + " <span class='remove-tag'>x</span></div>"); tagContainer.append(tagElement); // Add click event to remove tag tagElement.find(".remove-tag").click(function() { removeTag(tag); }); }); // Clear the input field $("#tag-input").val(""); } // Event listener for input field $("#tag-input").on("keypress", function(e) { if (e.which === 13 || e.which === 44) { // Enter key or comma key e.preventDefault(); var tag = $(this).val().trim(); if (tag !== "") { addTag(tag); } } }); });

This example uses jQuery to handle user input, add and remove tags, and update the display. The tags are displayed as rounded rectangles with a remove button ('x'). Adjust the styles and functionality as needed for your specific requirements.