JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.10.0/themes/black-tie/jquery-ui.css">
<div class="ui-widget">
<input id="tags" size="50" />
</div>
JavaScript
$(function () {
var source = ['Adam', 'Benjamin', 'Matt', 'Michael', 'Sam', 'Tim'];
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
$("#tags")
// don't navigate away from the field on tab when selecting an item
.on("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function (request, response) {
var term = $.ui.autocomplete.escapeRegex(extractLast(request.term))
, startsWithMatcher = new RegExp("^" + term, "i")
, startsWith = $.grep(source, function(value) {
return startsWithMatcher.test(value.label || value.value || value);
})
, containsMatcher = new RegExp(term, "i")
, contains = $.grep(source, function (value) {
return $.inArray(value, startsWith) < 0 &&
containsMatcher.test(value.label || value.value || value);
});
// delegate back to autocomplete, but extract the last term
response(startsWith.concat(contains));
},
focus: function () {
// prevent value inserted on focus
return false;
},
select: function (event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
});