I want to some tags by default witch show up time of open the page. This code normally working fine as add tags but when I trying some tags default such as java, html, php etc then code normally working but no show up default tags. Below is my code, please advice me how to do
JavaScript:
If you want to have some default tags like “java”, “html”, and “php” show up when the page opens, you will need to modify your window.onload function to create these tag elements and append them to your tags-container element when the page is loaded.
Here’s an updated version of your JavaScript code:
function setupTagInput(containerSelector) {
const container = document.querySelector(containerSelector);
const inputElement = container.querySelector('.tag-input');
const tagsContainer = container.querySelector('.tags-container');
const removeTag = (event) => {
if (event.target.classList.contains('tag-close')) {
event.target.parentElement.remove();
}
};
const addTag = (value) => {
const spanElement = document.createElement('span');
spanElement.innerHTML = `
<span class="tag-text">${value}</span>
<span class="tag-close">⌫</span>
`;
spanElement.classList.add('tag');
tagsContainer.appendChild(spanElement);
};
const handleKeyUp = (event) => {
if (event.keyCode === 13) {
const value = inputElement.value.trim();
if (value) {
addTag(value);
inputElement.value = '';
}
}
};
// Set up the default tags for this container
const defaultTags = container.dataset.defaultTags ? container.dataset.defaultTags.split(',') : [];
defaultTags.forEach(tag => {
addTag(tag);
});
// Adding event listeners
tagsContainer.addEventListener('click', removeTag);
inputElement.addEventListener('keyup', handleKeyUp);
}
// Set up all tag inputs on the page
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('.tag-input-container').forEach(container => {
setupTagInput(`#${container.id}`);
});
});
Your HTML would look like this for each tag system instance:
<div id="tag-container-1" class="tag-input-container" data-default-tags="java,html,php">
<div class="input-container">
<input type="text" placeholder="Type in something..." class="tag-input" />
</div>
<div class="tags-container">
<!-- Tags will be added here -->
</div>
</div>
<div id="tag-container-2" class="tag-input-container" data-default-tags="css,javascript,ruby">
<!-- Similar structure to the above -->
</div>
<!-- Repeat the above structure for as many tag systems as you need on the page -->
I got a problem, The default tags value doesn’t insert into the MySQL database but new tags values inserted and I also want to do press comma instead of hit Enter. Could you please let me know how to solve it. Thanks in advance.