How can you determine if a sentence was selected from a jQuery UI auto-complete

I have a text box that is connected to jQuery UI autocomplete. When a user types in a box, my search is done through an ajax call and returns suggestions. It seems that three things can happen:

  • Autofill offers options, and the user selects one of them.
  • Autocomplete offers options, but the user selects none of them.
  • Autocomplete cannot make an offer - there is no match (therefore, the list of offers is not displayed)

Working with all the scenarios described above, how can I determine if the user selects an option from autocomplete?

I looked for the flag flag when the search starts (match = false) and the selection (match = true) occurs, but this does not seem to be a very neat way to do things.

+5
source share
3 answers

You can use an event select, for example @bfavaretto , but I think that in this situation it is more convenient to use an event change:

$("#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/

changeit works when the field is blurry, but unlike the native event, changeyou get information about whether the user clicked the event or not ( ui.itemnull if the user did not click the sentence).

+11

, "". .

(function() {
    var optionSelected = false;
    $( ".selector" ).autocomplete({
        select: function(event, ui) { optionSelected = true; }
    });
})();
+2

jQueryUI provides an selectevent , you must define it in the autocomplete options (when applying autocomplete to form input).

For example (from docs ):

$( ".selector" ).autocomplete({
   select: function(event, ui) { ... }
});

You can access the selected item through the ui.iteminside of the event handler.

+1
source

All Articles