开发者

Changing the way autocomplete search works

Currently I have:

$("#location").autocomplete({source: cities, minLength: 0, autoFocus: true});

The problem is that this plugin searches for matches anywhere inside the given inputs.

For example, if I enter "Bos" it suggests not only the word开发者_如何学Pythons that start with "Bos", but also the words that have "bos" in the middle.

How can I fix this?


Looks like you'll have to use the callback setting for the source option:

The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:

  • A request object, with a single property called "term", which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo".
  • A response callback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties). It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state. (source)

Untested:

$(function() {
    var options = ["Foo", "Bar", "Baz", "Foobar"];

    $(<selector>).autocomplete({
        source: function(request, response) {
                    var matches = [],
                        term = request.term.toLowerCase(),
                        termLen = term.length;

                    for (var i = 0, j = options.length; i < j; i++) {
                         if (options[i].substring(0, termLen).toLowerCase() == term) {
                             matches.push(options[i]);
                         }
                    }

                    response(matches);
            }
    });
});


This is easy in the jQuery Autocomplete plugin, whose documentation answers this:

matchContains | Boolean | Default: false

Whether or not the comparison looks inside (i.e. does "ba" match "foo bar") the search results. Important only if you use caching. Don't mix with autofill.

You may wish to switch to this from jQuery UI Autocomplete as it's more fully-featured.


As @jensgram said You could use source method.

Something like that works for me in my web-app:

$("#location").autocomplete({
    source : function(request, response) {
        /* cities.html?query=... should return json array words starting with query value */
        $.getJSON('cities.html?query=' + request.term, function(data) {
            response(data);
        });
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜