Skip to content

Instantly share code, notes, and snippets.

@0smr
Created February 28, 2022 05:59
Show Gist options
  • Save 0smr/581b31718adc876c19181bec9fc1cf5e to your computer and use it in GitHub Desktop.
Save 0smr/581b31718adc876c19181bec9fc1cf5e to your computer and use it in GitHub Desktop.
simple HTML tag input

Tag input

simple tag input.

usage

  1. Add CSS and JS files. <link href = "simple-tag-input.css" rel = "stylesheet"> <script src = "simple-tag-input.js"></script>
  2. Simply put <input value="tag1,tag2,tag3" class="c1 c2 cn" placeholder="Enter tags." taged>.
  3. Enjoy.

Note: input must have taged attribute.

  • Enter values and press ('NumpadEnter' or 'Tab' or 'Space' or 'Enter') to insert the tags.
  • Click on tags to remove the tags.
  • Values are stored in input (comma seprated format).

You can check demo here https://codepen.io/smr76/pen/wvPYGaW.

label.tag {
background-color: white;
border: 1px #adc3e7 solid;
display: inline-block;
padding: 2px 8px;
margin: 0px 3px;
margin-top: 2px;
border-radius: 3px;
cursor: pointer;
}
input[hidden] {
visibility: hidden;
}
label.tag:hover {
border: 1px #ff6f6f solid;
background-color: #f5ecec;
}
function createTagElement(htmlValue, mainInput) {
let tag = document.createElement('label', {});
tag.classList.add('tag')
tag.addEventListener('click', function() {
const regex = new RegExp(`(\\b|,)${this.innerHTML}\\b`,'g');
mainInput.value = mainInput.value.replace(regex,""); // remove tag from input value
this.remove(); // remove tag itself
});
tag.innerHTML = htmlValue;
return tag;
}
function smrSimpleTagInput() {
let tagInputs = document.querySelectorAll('[taged]');
for(let input of tagInputs) {
input.setAttribute('hidden','hidden');
let fakeInput = document.createElement('input',{type: 'text'});
fakeInput.classList = input.classList;
fakeInput.mainPair = input;
fakeInput.setAttribute('type','text');
fakeInput.setAttribute('fakeinput','');
fakeInput.placeholder = input.placeholder ?? "";
fakeInput.addEventListener('keydown', function(e) {
const trValue = this.value.trim();
if( ['NumpadEnter','Tab','Space','Enter'].includes(e.code) && trValue.length) {
if(!this.mainPair.value.match(`\\b${trValue}\\b`)) {
let tag = createTagElement(trValue, this.mainPair);
this.mainPair.value += ',' + trValue;
this.after(tag); // add tag before input element.
}
this.value = ""; // reset value.
e.preventDefault();
}
})
input.after(fakeInput);
if(input.value.trim().length) {
let initVal = input.value.trim().split(',');
for(let val of initVal) {
if(val.length) {
let tag = createTagElement(val, input);
fakeInput.after(tag);
}
}
}
}
}
window.addEventListener('load', () => {
smrSimpleTagInput(window.MultiselectDropdownOptions);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment