jQuery UI Autocomplete with jsfiddle echo json
http://bugs.jqueryui.com/ticket/7230
by bryiantan
HTML
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/themes/base/jquery-ui.css">
<input id="autocomplete">
CSS
body {
font:62.5% Verdana, Arial, sans-serif;
}
JavaScript
var availableTags = [
"Bird",
"Son",
"ồk ko",
"Happy"];
function split(val) {
return val.split(/,\s*/);
}
function checkAvailable(term) {
var length = term.length,
chck = false,
term = term.toLowerCase();
for (var i = 0, z = availableTags.length; i < z; i++)
if (availableTags[i].substring(0, length).toLowerCase() === term) return true;
return false;
}
function extractLast(term) {
return split(term).pop();
}
var $autocomplete = $("#autocomplete")
// 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("ui-autocomplete").menu.active) {
event.preventDefault();
}
})
.on("keyup", function (event) {
var ac_value = this.value;
if (!checkAvailable(extractLast(ac_value))) this.value = ac_value.substring(0, ac_value.length - 1);
})
.autocomplete({
minLength: 0,
source: function (request, response) {
// delegate back to autocomplete, but extract the last term
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term)));
},
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;
}
});