How can I change the result filter in Autocomplete?

社会主义新天地 提交于 2019-12-05 08:50:13

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.

Abdul Kader

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

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