How to filter your jquery autocomplete data while typing

前端 未结 4 1732
清酒与你
清酒与你 2020-12-16 07:19

So far I have the following

var aCleanData = [\'aaa\',\'aab\',\'faa\',\'fff\',\'ffb\',\'fgh\',\'mmm\',\'maa\'];

$(\'#my-input\').autocomplete({
    source:a         


        
4条回答
  •  臣服心动
    2020-12-16 07:57

    After looking at the source for autocomplete, you have a few options. You could write your own pasrer method that returns what you need and set it as the callback source. This is probably the more "correct" way to do it.

    The faster way is to simply add the following line AFTER you include the ui source:

    $.ui.autocomplete.escapeRegex=function(){ 
        return '[^|\s]' + $value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");   
    };
    

    If you care how this works (or should work, I have not tested):

    The original code extends the ui.autocomplete with 2 static functions:

    $.extend( $.ui.autocomplete, {
    escapeRegex: function( value ) {
        return value.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
    },
    filter: function(array, term) {
        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
        return $.grep( array, function(value) {
            return matcher.test( value.label || value.value || value );
        });
    }
    });
    

    All you should need to do is change what escapeRegex returns to search for the beginning if words only. By setting the value of escapeRegex to return '[^|\s]' in front of the original return, we are saying "Look for the work with a space in front or is the beginning of a line"

提交回复
热议问题