JSFiddle - React, Tailwind, and code Playground
by vijayP
HTML
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css">
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<div id="tagsContainer">
<select id="Tags" multiple="" name="Tags">
<option value="white">white</option>
<option value="green">green</option>
</select>
</div>
CSS
#Tags{
width:300px;
}
JavaScript
$(document).ready(function() {
var data = [{ id: 0, name:'yellow', text: 'yellow' },
{ id: 1, name:'green', text: 'green' },
{ id: 2, name:'cyan', text: 'cyan' },
{ id: 3, name:'violet', text: 'violet' },
{ id: 4, name:'gray', text: 'gray' }
];
var uniqueTexts = null;
$("#Tags").select2({
tags: true,
data: data,
templateResult: tagFormatResult,
escapeMarkup: function (markup) {
uniqueTexts = null;
return markup;
},
matcher: function (params, data) {
if(!uniqueTexts){
uniqueTexts = [];
}
var modifiedData = null;
if ($.trim(params.term) === '' || data.text.indexOf(params.term) > -1) {
if(uniqueTexts.indexOf(data.text) == -1)
{
modifiedData = data;
uniqueTexts.push(modifiedData.text);
}
}
if(modifiedData)
{
return modifiedData;
}
return null;
}
});
function tagFormatResult(tag) {
if (tag.loading) {
return "Loading . . . <img src='/Content/Images/ajax-loader.gif' />";
}
else
{
var length = $('#tagsContainer .select2-selection__choice').filter(function () {
return $(this).attr("title").toUpperCase() === tag.text.toUpperCase();
}).length;
if (length == 1) {
return tag.text;
}
if (tag.text) {
if(getOptionCount(tag.text) >1)
return tag.text;
else
return tag.text + " [NEW]";
}
return tag.text + " [NEW]";
}
}
function getOptionCount(tagText)
{
var count = 0;
var selectBoxOptions = $("#Tags option");
$(selectBoxOptions).each(function(){
if(tagText == $(this).text())
count++;//increment the counter if option text is matching with tag text
});
return count;
}
});