chrispitzer
chrispitzer

Reputation: 1069

filtering jqueryUI autocomplete options

I'm using the jqueryUI autocomplete widget on my site. Say i have the following items in my database...

When I type "a" in the autocomplete widget i get that list below my input field. I've written additional code such that when you select an item it is added to a UL below the input field and the input field is cleared.

So, you type "a", you see that list, and you select apple. Apple is now an LI in the UL below the input field. You now type "a" again, and you see the list again... Here's my problem.

This second time I want to show everything EXCEPT apple.

I'd love to know how to do this in two different places:

1 - i'd love to know how to intercept the event that fires a GET query to the server, so that instead of sending "q=a" to the server when you type "a", i could make it send "q=a&exclude=apple,foo,bar". Then I filter the list server side and everything's good.

2 - I'd also love to know how to intercept the event that builds the list of options. That way, I could see that it's about to display the options "apple, ape, etc" and I could snip "apple" out of that list.

I see the events in the docs - but I'm not sure how to use them to accomplish the goals stated above.

Thanks!

Upvotes: 3

Views: 1474

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

You can accomplish both of these by defining a function for the source option of the autocomplete widget. From there, you'd perform the AJAX request yourself with $.ajax. Something like:

$("input").autocomplete({
    source: function (request, response) {
        var exclude = /* build excluded items list. */;
        var term = request.term;

        $.ajax({
            url: "server.php",
            data: { q: term, exclude: exclude },
            dataType: "json",
            success: function(data) {
                /* Here, you could accomplish #2 by filtering items out of data */
                /* You must call the supplied callback to let the widget know what to suggest */
                response(data);
            }
        });

    }
});

I would imagine you would build the excluded items just by extracting the items already in the ul.

Upvotes: 2

Related Questions