问题
I have a textbox with autocomplete and I want to show the results only when the dot key .
is pressed.
I tried:
$("#tags").on("keypress", function () {
var keys = [];
keys.unshift(e.which);
if (String.fromCharCode(keys[0]) == ".") {
} else {
$("#tags").unbind();
}
});
However, $("#tags").unbind();
removes all the events from the textbox, and if I press the dot key again, the results won't show up.
How can I fix this? Live jsfiddle
回答1:
Here is a solution that emulates what visual studio does:
http://jsfiddle.net/xHy6n/2/
It stores the location of the last "." and uses anything after it as a filter for the autocomplete.
$(function () {
var availableTags = [
"ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++", "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran", "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl", "PHP", "Python", "Ruby", "Scala", "Scheme"];
var lastDot = -1;
$("#tags").autocomplete({
minLength: 0,
source: function (request, response) {
if (lastDot>=0) {
response($.ui.autocomplete.filter(
availableTags, extractLast(request.term.substring(lastDot+1))));
}
},
focus: function () {
return false;
},
select: function (event, ui) {
var terms = split(this.value);
terms.pop();
terms.push(ui.item.value);
terms.push("");
this.value = this.value.substr(0,lastDot+1);
this.value += terms.join("");
return false;
}
}).on("keypress", function (e) {
var keys = [];
keys.unshift(e.which);
if (String.fromCharCode(keys[0]) == ".") {
lastDot = $("#tags").val().length;
}
});
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
});
回答2:
Instead of binding/unbinding, you could try something like this (so you can toggle the activation/deactivation of the autocomplete by pressing .
:
$("#tags").on("keypress", function (e) {
var keys = [];
keys.unshift(e.which);
if (String.fromCharCode(keys[0]) == ".") {
if(autocomplete_flag == 0) {
autocomplete_flag = 1;
$(this).autocomplete( "enable" );
} else {
autocomplete_flag = 0;
$(this).autocomplete( "disable" );
}
}
});
like this: http://jsfiddle.net/darkajax/fEsN5/6/
来源:https://stackoverflow.com/questions/16531903/show-jquery-ui-autocomplete-only-when-a-special-key-is-pressed