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 ca开发者_如何学Cll and returns suggestions. It seems that three things can happen:
- The autocomplete suggests options and the user selects one of them
- The autocomplete suggests options but the user chooses to select none of them
- 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.
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).
When a user selects an option, the 'select' event is fired. You can listen to it and set a flag.
(function() {
var optionSelected = false;
$( ".selector" ).autocomplete({
select: function(event, ui) { optionSelected = true; }
});
})();
jQueryUI provides a select
event, you should define it in the autocomplete options (when you apply the autocomplete to your form input).
For example (from the docs):
$( ".selector" ).autocomplete({
select: function(event, ui) { ... }
});
You can access the selected item via ui.item
from inside the event handler.
精彩评论