I am trying to implement Bootstrap Tokenfield with Jquery Ui autocomplete and so far i was able to do that except the fact that i am not able to prevent duplicates in the input
This prevents listing items that have already been added as tokens:
$('.tokenfield').on('tokenfield:createdtoken tokenfield:removedtoken', function (event) {
var field = $(this);
var currentTokens = field.tokenfield('getTokens');
var originalSource = field.data('bs.tokenfield').options.autocomplete.source;
var newSource = originalSource.slice(); //clone original autocomplete source
for (var i = newSource.length - 1; i >= 0; i--) {
for (var j = currentTokens.length - 1; j >= 0; j--) {
if (JSON.stringify(currentTokens[j].label) == JSON.stringify(newSource[i])
|| JSON.stringify(currentTokens[j]) == JSON.stringify(newSource[i]) ) {
//remove the token from the newSource
var index = newSource.indexOf(newSource[i]);
if (index > -1)
newSource.splice(index, 1);
};
};
};
//update source
field.data('bs.tokenfield').$input.autocomplete({source: newSource})
})
This function is called after token is created or deleted to update the list. It uses JSON.stringify() to compare objects, and does the comparison for string objects and for {value: "foo", label: "bar"} source objects.