Возможно, это делает то, что вы хотите:
$( function() {
// Demo data -- store the data according to your need from database.
let availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
function getTermRemainder(str, p) {
let part1 = str.substring(0,p).split(',');
let part2 = str.substring(p).split(',');
let term = (part1.pop() + part2.shift()).trim();
part1 = part1.join(',').trim();
part2 = part2.join(',').trim();
let remainder = part1.length ? (
part2.length ? part1 + ', ' + part2 : part1
) : (
part2.length ? part2 : ''
);
return {
term: term,
remainder: remainder
};
}
$("#birds")
.autocomplete({
focus: function(e, ui) {
return false;
},
source: function(request, response) {
let start = this.element.get(0).selectionStart;
let { term, remainder } = getTermRemainder(request.term, start);
term = term.toLowerCase();
let terms = remainder.split(',');
let hash = {};
for(let i = 0, l = terms.length; i < l; i++)
hash[terms[i].trim()] = true;
let matched = availableTags
.filter(function(item) {
return(
item.toLowerCase().indexOf(term) !== -1 &&
!hash[item]
);
});
response(matched);
},
select: function(event, ui) {
let selected = ui.item.value;
let val = this.value;
let pos = this.selectionStart;
let start = pos;
while(--start > 0) if(val.charAt(start) === ',') break;
let end = pos-1;
let l = val.length;
while(++end < l) if(val.charAt(end) === ',') break;
let result = '';
if(start > 0) result += val.slice(0,start) + ', ';
result += selected;
if(end < l) result += val.slice(end);
else result += ', ';
this.value = result;
return false;
}
});
});
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Multiple values</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div class="ui-widget">
<label for="birds">Tag programming languages: </label>
<input id="birds" size="50">
</div>
</body>
</html>