Show Jquery UI Autocomplete only when a special key is pressed

僤鯓⒐⒋嵵緔 提交于 2019-12-08 04:53:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!