Код: Выделить всё
console.log("✅ Tagify script loaded");
const input = document.querySelector('#tags');
const tagify = new Tagify(input, {
maxTags: 5,
enforceWhitelist: false,
dropdown: {
enabled: 1,
fuzzySearch: true,
position: 'auto',
highlightFirst: true
}
});
let wasDuplicate = false;
tagify.on('beforeAddTag', function(e) {
const newTag = e.detail.data.value.toLowerCase();
const existingTags = tagify.value.map(tag => tag.value.toLowerCase());
if (existingTags.includes(newTag)) {
e.preventDefault();
wasDuplicate = true;
console.log("❌ Duplicate tag blocked:", newTag);
showError(`The tag "${newTag}" has already been added.`);
} else {
wasDuplicate = false;
console.log("✅ Unique tag allowed:", newTag);
clearError();
}
});
tagify.on('add', function(e) {
const addedTag = e.detail.data.value.toLowerCase();
if (wasDuplicate) {
console.log("🚫 Skipping add handler due to duplicate:", addedTag);
wasDuplicate = false;
return;
}
console.log('✅ Valid tag added:', addedTag);
clearError();
});
tagify.on('invalid', function(e) {
const invalidTag = e.detail.data.value;
const reason = e.detail.message || "This tag is not valid";
console.log("🔴 Invalid tag:", invalidTag, "Reason:", reason);
showError(reason);
});
// ✅ Split error functions for clarity
function showError(msg) {
const errorEl = document.getElementById('tag-error');
if (errorEl) {
errorEl.innerText = msg;
errorEl.style.display = 'block';
errorEl.style.color = 'red';
errorEl.style.fontSize = '0.875rem';
errorEl.style.minHeight = '1.5rem';
console.log("⚠️ Error displayed:", msg);
}
}
function clearError() {
const errorEl = document.getElementById('tag-error');
if (errorEl) {
errorEl.innerText = "";
errorEl.style.display = 'none';
console.log("✅ Error cleared");
}
}< /code>
#tag-error {
/* Just making sure the div is visible and spaced */
color: red;
font-size: 14px;
min-height: 24px;
margin-top: 5px;
}< /code>
Подробнее здесь: https://stackoverflow.com/questions/796 ... -incorrect