Merhaba arkadaşlar,
Script kodlarken konu içine etiket eklemek için kullandığım kodları paylaşıyorum. Umarım bu konuda sıkıntı yaşayanlara yardımcı olur.
Görsel için:
https://hizliresim.com/C7OmGg
Js Kodu:
const tagContainer = document.querySelector('.tag-container');
const input = document.querySelector('.tag-container input');
let tags = [];
function createTag(label) {
const div = document.createElement('div');
div.setAttribute('class', 'tag');
const input = document.createElement('input');
input.setAttribute('type', 'hidden');
input.setAttribute('name', 'thidden[]');
input.setAttribute('value', label);
const span = document.createElement('span');
span.setAttribute('name', 'etiket');
span.innerHTML = label;
const closeIcon = document.createElement('i');
closeIcon.setAttribute('class', 'fas fa-backspace');
closeIcon.setAttribute('style', 'color:red');
closeIcon.setAttribute('data-item', label);
div.appendChild(input);
div.appendChild(span);
div.appendChild(closeIcon);
return div;
}
function clearTags() {
document.querySelectorAll('.tag').forEach(tag => {
tag.parentElement.removeChild(tag);
});
}
function addTags() {
clearTags();
tags.slice().reverse().forEach(tag => {
tagContainer.prepend(createTag(tag));
});
}
input.addEventListener('keyup', (e) => {
if (e.which == 27) {
e.target.value.split(',').forEach(tag => {
tags.push(tag);
});
addTags();
input.value = '';
}
});
document.addEventListener('click', (e) => {
console.log(e.target.tagName);
if (e.target.tagName === 'I') {
const tagLabel = e.target.getAttribute('data-item');
const index = tags.indexOf(tagLabel);
tags = [...tags.slice(0, index), ...tags.slice(index+1)];
addTags();
}
})
input.focus();Kod Php:
$etiketbul=$this->input->post('thidden');
$birlestir = implode(',',$etiketbul); echo $birlestir;Kod Html:
<div class="tag-container">
<input />
</div>Javascript
: span tagı ile etiketi ekrana basar, ben etiketleri ayırmak için esc tuşunu kullandım. i tagı kırmızı silme butonunu oluşturur. input hidden ise etiketi post etmek için kullanılır. html kod ile etiket ekleme olayını istediğiniz yerde gösterebilirsiniz.
Herkese iyi çalışmalar.