Jquery Autocomplete matching multiple unordered words in a string

前端 未结 1 1855
时光说笑
时光说笑 2021-02-09 12:13

I am trying to show the best match of the search term typed in. For example

Right now Jquery does not give me the desired effect. When I type: one today

1条回答
  •  攒了一身酷
    2021-02-09 12:35

    Try overriding the default filter logic provided by auto complete.

    // Overrides the default autocomplete filter function to search for matched on atleast 1 word in each of the input term's words
    $.ui.autocomplete.filter = function (array, terms) {
        arrayOfTerms = terms.split(" ");
        var term = $.map(arrayOfTerms, function (tm) {
             return $.ui.autocomplete.escapeRegex(tm);
        }).join('|');
       var matcher = new RegExp("\\b" + term, "i");
        return $.grep(array, function (value) {
           return matcher.test(value.label || value.value || value);
        });
    };
    

    Fiddle

    Or create your own filter function and handle the search's return, so keeping complete's filter function as it is.

    function customFilter(array, terms) {
        arrayOfTerms = terms.split(" ");
        var term = $.map(arrayOfTerms, function (tm) {
             return $.ui.autocomplete.escapeRegex(tm);
        }).join('|');
       var matcher = new RegExp("\\b" + term, "i");
        return $.grep(array, function (value) {
           return matcher.test(value.label || value.value || value);
        });
    };
    
    $("#tags").autocomplete({
        source: availableTags,
        multiple: true,
        mustMatch: false
        ,source: function (request, response) {
            response(customFilter(
            availableTags, request.term));
        },
    });
    

    Fiddle

    0 讨论(0)
提交回复
热议问题