简体   繁体   中英

How can I change the result filter in Autocomplete?

Instead of making a literal match I'd like to select results by regular expression.

Can I override Autocomplete's default behavior to accomplish this or do I need an alternate structure?

There is a built-in way to do this: just provide a function for the source option in the autocomplete widget:

var items = ['Foo', 'Bar', 'Hello', 'Goodbye', '1234'];


$("#autocomplete").autocomplete({
    source: function(request, response) {
        // The term the user searched for;
        var term = request.term;

        // Extract matching items:
        var matches = $.grep(items, function(item, index) {
            // Build your regex here:
            return /\d+/.test(item);
        });

        // let autocomplete know the results:
        response(matches);
    }
});

http://jsfiddle.net/RSyrX/

Note that this example will always return "1234" because of the simple regular expression I used. Something more useful would probably be to build the regex based on the term (also possible).

This is actually very similar to the way that the widget itself filters results. Check out this line for the filter function and this line to see how it's called if you supply an array as the source option.

I've created an example in which only results containing the string 'jQuery' in the label are rendered:

var projects = [
    {
    value: "jquery",
    label: "jQuery",
    desc: "the write less, do more, JavaScript library",
    icon: "jquery_32x32.png"},
{
    value: "jquery-ui",
    label: "jQuery UI",
    desc: "the official user interface library for jQuery",
    icon: "jqueryui_32x32.png"},
{
    value: "sizzlejs",
    label: "Sizzle JS",
    desc: "a pure-JavaScript CSS selector engine",
    icon: "sizzlejs_32x32.png"}
];

$("input").autocomplete({
    source: projects
}).data("autocomplete")._renderItem = function(ul, item) {

    // this is where you can implement your regex
    if (item.label.indexOf("jQuery") !== -1) {
        return $("<li></li>").data("item.autocomplete", item).append("<a>" + item.label + "<br>" + item.desc + "</a>").appendTo(ul);
    }
};

Demo here.

Ya you can override jQueryUI's autocomplete's default behaviour. In your controller you should write your server side logic to generate the result set. jQuery autcomplete by default uses q as parameter. Using which you can get the values and generate the result set which will be a list. I think this will give you an idea. Autocomplete just displays the result on each key storke. You should take care of displaying logic

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM