Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you tell if a suggestion was selected from JQuery UI Autocomplete

I have a text box that is wired to JQuery UI Autocomplete. As the user types in the box my search runs via an ajax call and returns suggestions. It seems that three things can happen:

  1. The autocomplete suggests options and the user selects one of them
  2. The autocomplete suggests options but the user chooses to select none of them
  3. The autocomplete can not make a suggestion - no match (so the list of suggestions do not display)

Dealing with all of the scenarios above, how can I tell if the user selects an option from the autocomplete?

I have looked into marking a flag when a search commences (match=false) and a select occurs (match=true) but this doesn't seem a very neat way of doing things.

like image 481
Mark Robinson Avatar asked Sep 22 '11 15:09

Mark Robinson


1 Answers

You can use the select event like @bfavaretto points out, but I think in this situation it's more convenient to use the change event:

$("#auto").autocomplete({
    source: ['hi', 'bye', 'foo', 'bar'],
    change: function(event, ui) {
        if (ui.item) {
            $("span").text(ui.item.value);
        } else {
            $("span").text("user picked new value");
        }
    }
});

Example: http://jsfiddle.net/andrewwhitaker/3FX2n/

change fires when the field is blurred, but unlike the native change event, you get information about whether or not the user clicked an event (ui.item is null if the user did not click a suggestion).

like image 183
Andrew Whitaker Avatar answered Oct 18 '22 22:10

Andrew Whitaker