Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 853
user474632 Avatar asked May 18 '11 09:05

user474632


3 Answers

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.

like image 114
Andrew Whitaker Avatar answered Nov 06 '22 10:11

Andrew Whitaker


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.

like image 39
karim79 Avatar answered Nov 06 '22 12:11

karim79


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

like image 37
Abdul Kader Avatar answered Nov 06 '22 10:11

Abdul Kader